﻿using Adp;
using Adp.Common;
using Microsoft.AspNetCore.Mvc;
using Yqd.Core;
using Yqd.Enm;
using Yqd.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Yqd.Controllers.Filter;
using System.IO;
using OfficeOpenXml;
using Newtonsoft.Json;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class ZLDHomeController : Controller
    {
        YqdContext ctx;

        DdService ddService;

        public ZLDHomeController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        //总体效能
        //[HttpPost]
        [User]
        public ActionResult GetAllEvaluate()
        {
            var Year = Form.GetInt("Year", 0);
            var p = Form.GetInt("platform", 0);
            var LeaderUnitCode = Form.GetString("UnitCode");
            var Leader = Form.GetString("Leader", "王健");
            var Area = Form.GetString("Area");
            var TaskType = Form.GetString("TaskType", "");
            var where = "select TaskStatus, count(*) as Num from Yqd_Task where IsShow = 1";
            if (Year > 0)
            {
                where += " and [Year] = {0}";
            }
            if (!string.IsNullOrWhiteSpace(Area))
            {
                where += " and FAreaCode={1}";
            }
            if (TaskType != "")
            {
                where += " and (','+[TaskType]+',') like {4}";
            }
            if (Leader != "王健")
            {
                //if (Year > 2021)
                //{
                //where += " and substring(TaskPath,1,charindex('/',TaskPath)-1) in (Select TaskPath From Yqd_UnitLeader Where Leader={2} and [Year]={0})";
                //}
                //else
                //{
                where += " and ((LeaderUnitCode in (Select UnitCode From Yqd_Unit Where Leader={4})) or ConnectMan={4})";
                //}
            }
            if (!string.IsNullOrWhiteSpace(LeaderUnitCode))
            {
                var code = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == LeaderUnitCode)?.OrganizationCode ?? "";
                where += " and ((','+LeaderUnitCode+',') like {3} or LeaderUnitCode='" + code + "')";
            }
            where += " group by TaskStatus";
            where += " order by TaskStatus";
            var list = ctx.Database.SqlQuery<TaskStatusTJ>(where, Year, Area, Leader, "%," + LeaderUnitCode + ",%", "%," + TaskType + ",%").ToList();
            var Count = list.Sum(it => it.Num);
            var IRL = ctx.Yqd_IntegralRule.ToList();
            var WCV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.已完成).Value;
            var ZCV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.正常推进).Value;
            var YJV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.预警).Value;
            var ZHV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.滞后).Value;

            var WC = list.FirstOrDefault(it => it.TaskStatus == (int)任务状态.已完成)?.Num ?? 0;
            var ZC = list.FirstOrDefault(it => it.TaskStatus == (int)任务状态.正常推进)?.Num ?? 0;
            var YJ = list.FirstOrDefault(it => it.TaskStatus == (int)任务状态.预警)?.Num ?? 0;
            var ZH = list.FirstOrDefault(it => it.TaskStatus == (int)任务状态.滞后)?.Num ?? 0;

            //完成的总积分
            var WCS = WC * WCV;
            //正常的总积分
            var ZCS = ZC * ZCV;
            //预警的总积分
            var YJS = YJ * YJV;
            //预警的总积分
            var ZHS = ZH * ZHV;
            //计算平均分
            var AvgScore = Count == 0 ? 0 : (WCS + ZCS + YJS + ZHS) / Count;
            var Score = Math.Round(AvgScore, 2);
            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    Count,
                    Score,
                    WC,
                    ZC,
                    YJ,
                    ZH
                }
            });
        }

        //历史趋势
        //[HttpPost]
        [User]
        public ActionResult GetAllEvaluateLog()
        {
            var p = Form.GetInt("platform", 0);
            var year = Form.GetInt("Year", 0);
            //var UnitCode = Form.GetString("UnitCode", p == 1 ? "330782000000" : WxUser.LogonInfo.UnitCode);
            var UnitCode = Form.GetString("UnitCode", p == 2 ? WxUser.LogonInfo.UnitCode : year > 2021 ? "" : "330782000000");
            var Area = Form.GetString("Area", "");
            var TaskType = Form.GetString("TaskType", "");
            var dt = DateTime.Now;
            if (year > 2021)
            {
                var rank = ctx.Yqd_NewRank.Where(it => it.FAreaCode == Area && it.UnitCode == UnitCode && it.Year == year && ("," + it.TaskType + ",").Contains("," + TaskType + ",") && it.ResultTime < dt).OrderByDescending(it => it.ResultTime).ToList();
                return this.ToJson(new
                {
                    success = true,
                    data = rank.Select(it => new
                    {
                        it.Score,
                        DateTime = it.ResultTime.ToString("MM月dd日")
                    })
                });
            }
            else
            {
                var YiWuList = ctx.Yqd_Rank.Where(it => it.UnitCode == UnitCode && it.ResultTime.Year == year && it.ResultTime < dt).OrderByDescending(it => it.ResultTime).ToList();
                switch (Area)
                {
                    case "330000000000":
                        YiWuList = YiWuList.Where(it => it.Score_330000 > 0).ToList();
                        break;
                    case "330700000000":
                        YiWuList = YiWuList.Where(it => it.Score_330700 > 0).ToList();
                        break;
                    case "330782000000":
                        YiWuList = YiWuList.Where(it => it.Score_330782 > 0).ToList();
                        break;
                    default:
                        YiWuList = YiWuList.Where(it => it.Score > 0).ToList();
                        break;
                }
                return this.ToJson(new
                {
                    success = true,
                    data = YiWuList.Select(it => new
                    {
                        Score = Area.Trim() == "" ? it.Score : (Area == "330000000000" ? it.Score_330000 : (Area == "330700000000" ? it.Score_330700 : it.Score_330782)),
                        DateTime = it.ResultTime.ToString("MM月dd日")
                    })
                });
            }

        }

        //总体效能
        //[HttpPost]
        [User]
        public ActionResult GetAllTaskRank()
        {
            var Year = Form.GetInt("Year", 0);
            var p = Form.GetInt("platform", 0);
            var LeaderUnitCode = Form.GetString("UnitCode");
            var Leader = Form.GetString("Leader", "王健");
            var Area = Form.GetString("Area");
            var TaskType = Form.GetString("TaskType", "");
            var where = "SELECT    TaskStatus, COUNT(*) AS Num FROM Yqd_Task WHERE IsShow = 1";
            if (Year > 0)
            {
                where += " and [Year] = {0}";
            }
            if (!string.IsNullOrWhiteSpace(Area))
            {
                where += " and FAreaCode={1}";
            }
            if (TaskType != "")
            {
                where += " and (','+[TaskType]+',') like {4}";
            }
            //if (Leader != "王健")
            //{
            //    where += " and ((LeaderUnitCode in (Select UnitCode From Yqd_Unit Where Leader={2})) or ConnectMan={2})";

            //    //if (Year > 2021)
            //    //{
            //    //    where += " and SUBSTRING(TaskPath,1,CHARINDEX('/',TaskPath)-1) in (Select TaskPath From Yqd_UnitLeader Where Leader={2} and [Year]={0})";
            //    //}
            //    //else
            //    //{
            //    //    where += " and LeaderUnitCode in (Select UnitCode From Yqd_Unit Where Leader={2})";
            //    //}
            //}

            if (Leader != "王健")
            {
                where += $@" and (
LeaderUnitCode in (
select OrganizationCode from Yqd_Unit where UnitCode in (Select substring(a.unit, b.number, charindex(',', a.unit + ',', b.number) - b.number) From Yqd_UnitLeader a inner join master.dbo.spt_values b on b.number between 1 and len(a.unit) Where a.Leader = '{Leader}' and a.unit != '' {(Year > 0 ? " and a.year=" + Year : "")} or ConnectMan = '{Leader}'))
or
LeaderUnitCode in (
select UnitCode from Yqd_Unit where UnitCode in (Select substring(a.unit, b.number, charindex(',', a.unit + ',', b.number) - b.number) From Yqd_UnitLeader a inner join master.dbo.spt_values b on b.number between 1 and len(a.unit) Where a.Leader = '{Leader}' and a.unit != '' {(Year > 0 ? " and a.year=" + Year : "")} or ConnectMan = '{Leader}'))
)";
            }
            if (!string.IsNullOrWhiteSpace(LeaderUnitCode))
            {
                var code = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == LeaderUnitCode)?.OrganizationCode ?? "";
                where += " and ((','+LeaderUnitCode+',') like {3} or LeaderUnitCode='" + code + "')";
            }
            where += " GROUP BY TaskStatus";
            where += " ORDER BY TaskStatus";
            var list = ctx.Database.SqlQuery<TaskStatusTJ>(where, Year, Area, Leader, "%," + LeaderUnitCode + ",%", "%," + TaskType + ",%").ToList();
            var Count = list.Sum(it => it.Num);
            var IRL = ctx.Yqd_IntegralRule.ToList();
            var WCV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.已完成).Value;
            var ZCV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.正常推进).Value;
            var YJV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.预警).Value;
            var ZHV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.滞后).Value;

            var WC = list.FirstOrDefault(it => it.TaskStatus == (int)任务状态.已完成)?.Num ?? 0;
            var ZC = list.FirstOrDefault(it => it.TaskStatus == (int)任务状态.正常推进)?.Num ?? 0;
            var YJ = list.FirstOrDefault(it => it.TaskStatus == (int)任务状态.预警)?.Num ?? 0;
            var ZH = list.FirstOrDefault(it => it.TaskStatus == (int)任务状态.滞后)?.Num ?? 0;

            //完成的总积分
            var WCS = WC * WCV;
            //正常的总积分
            var ZCS = ZC * ZCV;
            //预警的总积分
            var YJS = YJ * YJV;
            //预警的总积分
            var ZHS = ZH * ZHV;
            //计算平均分
            var AvgScore = Count == 0 ? 0 : (WCS + ZCS + YJS + ZHS) / Count;
            var Score = Math.Round(AvgScore, 2);

            var aScore = Count == 0 ? 0 : (WC * 1.0) / (Count * 1.0);
            var WCRank = Math.Round(aScore * 100, 2);
            aScore = Count == 0 ? 0 : (ZC * 1.0) / (Count * 1.0);
            var ZCRank = Math.Round(aScore * 100, 2);
            aScore = Count == 0 ? 0 : (YJ * 1.0) / (Count * 1.0);
            var YJRank = Math.Round(aScore * 100, 2);
            aScore = Count == 0 ? 0 : (ZH * 1.0) / (Count * 1.0);
            var ZHRank = Math.Round(aScore * 100, 2);
            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    Count,
                    Score,
                    WC,
                    WCRank = WCRank + "%",
                    ZC,
                    ZCRank = ZCRank + "%",
                    YJ,
                    YJRank = YJRank + "%",
                    ZH,
                    ZHRank = ZHRank + "%"
                }
            });
        }

        //各级任务
        [User]
        public ActionResult GetTaskRank()
        {
            var year = Form.GetInt("Year", 0);
            var TaskType = Form.GetString("TaskType", "");
            var task = ctx.Yqd_Task.Where(it => it.IsShow);
            if (year > 0)
            {
                task = task.Where(it => it.Year == year + "");
            }
            if (TaskType != "")
            {
                task = task.Where(it => ("," + it.TaskType + ",").Contains("," + TaskType + ","));
            }
            var Count = task.Count();
            var data = new List<object>();
            var zCount = task.Count(it => it.FAreaCode == "330000000000");
            var AvgScore = Count == 0 ? 0 : (zCount * 0.1) / (Count * 0.1);
            var Rank = Math.Round(AvgScore * 100, 2);
            data.Add(new
            {
                Name = "浙江省",
                Count = zCount,
                Rank = Rank + "%"
            });
            zCount = task.Count(it => it.FAreaCode == "330700000000");
            AvgScore = Count == 0 ? 0 : (zCount * 0.1) / (Count * 0.1);
            Rank = Math.Round(AvgScore * 100, 2);
            data.Add(new
            {
                Name = "金华市",
                Count = zCount,
                Rank = Rank + "%"
            });
            zCount = task.Count(it => it.FAreaCode == "330782000000");
            AvgScore = Count == 0 ? 0 : (zCount * 0.1) / (Count * 0.1);
            Rank = Math.Round(AvgScore * 100, 2);
            data.Add(new
            {
                Name = "义乌市",
                Count = zCount,
                Rank = Rank + "%"
            });
            return this.ToJson(new
            {
                success = true,
                data
            });
        }

        //单位效能指数
        //[HttpPost]
        [User]
        public ActionResult GetUnitRank()
        {
            var Size = Form.GetInt("Size", 250);
            var pType = Form.GetInt("pType", 0);
            var px = Form.GetString("px", "desc");
            var Area = Form.GetString("Area");
            var Leader = Form.GetString("Leader", "王健");
            var TaskType = Form.GetString("TaskType", "");
            var Year = Form.GetInt("Year", 2022);
            //var Year = Form.GetInt("Year", 2023);
            var where = "SELECT LeaderUnitCode as UnitCode, LeaderUnitName as UnitName, TaskStatus, COUNT(*) AS Num FROM Yqd_Task WHERE IsShow = 1";
            if (Year > 0)
            {
                where += " and [Year] = {0}";
            }
            if (!string.IsNullOrWhiteSpace(Area))
            {
                where += " and FAreaCode={1}";
            }
            if (Leader != "王健")
            {
                where += " and ((LeaderUnitCode in (Select UnitCode From Yqd_Unit Where Leader={2})) or ConnectMan={2})";
            }
            if (TaskType != "")
            {
                where += " and (','+[TaskType]+',') like {3}";
            }
            where += " GROUP BY LeaderUnitCode,LeaderUnitName,TaskStatus";
            var list = ctx.Database.SqlQuery<TaskStatusTJ>(where, Year, Area, Leader, "%," + TaskType + ",%").ToList();
            var unit = list.Select(it => new
            {
                it.UnitCode,
                it.UnitName
            }).Distinct();
            var IRL = ctx.Yqd_IntegralRule.ToList();
            var WCV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.已完成).Value;
            var ZCV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.正常推进).Value;
            var YJV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.预警).Value;
            var ZHV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.滞后).Value;
            var RankList = new List<Yqd_Rank>();
            foreach (var m in unit)
            {
                var ml = list.Where(it => it.UnitCode == m.UnitCode);
                var Count = ml.Sum(it => it.Num);
                var WC = ml.FirstOrDefault(it => it.TaskStatus == (int)任务状态.已完成)?.Num ?? 0;
                var ZC = ml.FirstOrDefault(it => it.TaskStatus == (int)任务状态.正常推进)?.Num ?? 0;
                var YJ = ml.FirstOrDefault(it => it.TaskStatus == (int)任务状态.预警)?.Num ?? 0;
                var ZH = ml.FirstOrDefault(it => it.TaskStatus == (int)任务状态.滞后)?.Num ?? 0;
                //完成的总积分
                var WCS = WC * WCV;
                //正常的总积分
                var ZCS = ZC * ZCV;
                //预警的总积分
                var YJS = YJ * YJV;
                //预警的总积分
                var ZHS = ZH * ZHV;
                //计算平均分
                var AvgScore = Count == 0 ? 0 : (WCS + ZCS + YJS + ZHS) / Count;
                var Score = Math.Round(AvgScore, 2);
                var task = ctx.Yqd_Task.Where(x => x.LeaderUnitCode == m.UnitCode).OrderByDescending(x => x.InsTime).FirstOrDefault();
                RankList.Add(new Yqd_Rank
                {
                    Name = m.UnitName,
                    UnitCode = m.UnitCode,
                    Score = Score,
                    Count = Count,
                    ResultTime = task.InsTime
                });
            }
            if (px == "asc")
            {
                RankList = RankList.OrderBy(it => pType == 0 ? it.Score : it.Count).Take(Size).ToList();
            }
            else
            {
                //RankList = RankList.OrderByDescending(it => pType == 0 ? it.Score : it.Count).ThenByDescending(it => it.ResultTime).Take(Size).ToList();
                RankList = RankList.OrderByDescending(it => pType == 0 ? it.Score : it.Count).ThenByDescending(it => pType == 0 ? it.Count : it.Score).ThenByDescending(it => it.ResultTime).Take(Size).ToList();
            }
            return this.ToJson(new
            {
                success = true,
                data = RankList.Select(it => new
                {
                    it.Name,
                    it.UnitCode,
                    it.Count,
                    it.Score
                })
            });
        }

        public ActionResult GetRank()
        {
            var RankID = Form.GetInt("RankID", 0);
            var Rank = ctx.Yqd_Rank.FirstOrDefault(it => it.RankID == RankID);
            if (Rank == null)
            {
                return this.ToJson(new
                {
                    success = true,
                    msg = "效能信息为空"
                });

            }

            var zhTask = ctx.Yqd_Task.Where(it => it.TaskStatus == (int)Enm.任务状态.滞后 && it.IsShow && (it.LeaderUnitCode == Rank.UnitCode)).OrderByDescending(it => it.CreateTime).Select(it => new
            {
                it.TaskName,
                TaskID = it.TaskID.ToString()
            }).ToList();
            var yjTask = ctx.Yqd_Task.Where(it => it.TaskStatus == (int)Enm.任务状态.预警 && it.IsShow && (it.LeaderUnitCode == Rank.UnitCode)).OrderByDescending(it => it.CreateTime).Select(it => new
            {
                it.TaskName,
                TaskID = it.TaskID.ToString()
            }).ToList();
            var zcTask = ctx.Yqd_Task.Where(it => it.TaskStatus == (int)Enm.任务状态.正常推进 && it.IsShow && (it.LeaderUnitCode == Rank.UnitCode)).OrderByDescending(it => it.CreateTime).Select(it => new
            {
                it.TaskName,
                TaskID = it.TaskID.ToString()
            }).ToList();
            var wcTask = ctx.Yqd_Task.Where(it => it.TaskStatus == (int)Enm.任务状态.已完成 && it.IsShow && it.IsShow && (it.LeaderUnitCode == Rank.UnitCode)).OrderByDescending(it => it.CreateTime).Select(it => new
            {
                it.TaskName,
                TaskID = it.TaskID.ToString()
            }).ToList();


            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    Rank.Name,
                    ResultTime = Rank.ResultTime.ToString("yyyy-MM-dd"),
                    Rank.Score,
                    Tactic = Rank.UnitCode == "330782000000" ? "--" : Rank.Tactic.ToString(),
                    Rank.UnitCode,
                    ZHTask = new
                    {
                        Type = Enm.任务状态.滞后.ToString(),
                        Rank.ZH,
                        list = zhTask,
                    },
                    YJTask = new
                    {
                        Type = Enm.任务状态.预警.ToString(),
                        Rank.YJ,
                        //Area.Trim() == "" ? yiwu.YJ : (Area == "330000000000" ? yiwu.YJ_330000 : (Area == "330700000000" ? yiwu.YJ_330700 : yiwu.YJ_330782)),
                        list = yjTask,
                    },
                    ZCTask = new
                    {
                        Type = Enm.任务状态.正常推进.ToString(),
                        Rank.ZC, //Area.Trim() == "" ? yiwu.ZC : (Area == "330000000000" ? yiwu.ZC_330000 : (Area == "330700000000" ? yiwu.ZC_330700 : yiwu.ZC_330782)),
                        list = zcTask,
                    },
                    WCTask = new
                    {
                        Type = Enm.任务状态.已完成.ToString(),
                        Rank.WC,// Area.Trim() == "" ? yiwu.WC : (Area == "330000000000" ? yiwu.WC_330000 : (Area == "330700000000" ? yiwu.WC_330700 : yiwu.WC_330782)),
                        list = wcTask,
                    }
                },

            });

        }
        //历史效能评价报告
        //[HttpPost]
        [User]
        public ActionResult TaskLog()
        {
            var Take = Form.GetInt("Take", 3);
            var p = Form.GetInt("platform", 0);
            var year = Form.GetInt("Year", 0);
            var TaskType = Form.GetString("TaskType", "");
            var UnitCode = Form.GetString("UnitCode", p == 2 ? WxUser.LogonInfo.UnitCode : "330782000000");
            var Area = Form.GetString("Area");
            var r = ctx.Yqd_Rank.Where(it => it.UnitCode == UnitCode);
            if (year > 0) r = r.Where(it => it.ResultTime.Year == year);
            var MaxResultTime = r.OrderByDescending(it => it.ResultTime).First()?.ResultTime;
            var yiwu = r.FirstOrDefault(it => it.ResultTime == MaxResultTime);
            if (yiwu == null) yiwu = new Yqd_Rank();
            var t = ctx.Yqd_Task.Where(it => it.IsShow);
            if (year > 0)
            {
                t = t.Where(it => it.Year == year + "");
            }
            if (TaskType != "")
            {
                t = t.Where(it => ("," + it.TaskType + ",").Contains("," + TaskType + ","));
            }
            var task = t.Select(it => new { TaskID = it.TaskID.ToString(), it.TaskName, it.LeaderUnitCode, it.FAreaCode, it.TaskStatus, it.CreateTime }).ToList();
            var zhTask = task.Where(it => it.TaskStatus == (int)任务状态.滞后 && (UnitCode != "330782000000" ? it.LeaderUnitCode == UnitCode : UnitCode == "330782000000") && (Area.Trim() == "" ? true : (it.FAreaCode == Area))).OrderByDescending(it => it.CreateTime).Take(Take).Select(it => new
            {
                it.TaskName,
                it.TaskID
            }).ToList();
            var yjTask = task.Where(it => it.TaskStatus == (int)任务状态.预警 && (UnitCode != "330782000000" ? it.LeaderUnitCode == UnitCode : UnitCode == "330782000000") && (Area.Trim() == "" ? true : (it.FAreaCode == Area))).OrderByDescending(it => it.CreateTime).Take(Take).Select(it => new
            {
                it.TaskName,
                it.TaskID
            }).ToList();
            var zcTask = task.Where(it => it.TaskStatus == (int)任务状态.正常推进 && (UnitCode != "330782000000" ? it.LeaderUnitCode == UnitCode : UnitCode == "330782000000") && (Area.Trim() == "" ? true : (it.FAreaCode == Area))).OrderByDescending(it => it.CreateTime).Take(Take).Select(it => new
            {
                it.TaskName,
                it.TaskID
            }).ToList();
            var wcTask = task.Where(it => it.TaskStatus == (int)任务状态.已完成 && (UnitCode != "330782000000" ? it.LeaderUnitCode == UnitCode : UnitCode == "330782000000") && (Area.Trim() == "" ? true : (it.FAreaCode == Area))).OrderByDescending(it => it.CreateTime).Take(Take).Select(it => new
            {
                it.TaskName,
                it.TaskID
            }).ToList();
            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    ZHTask = new
                    {
                        Type = Enm.任务状态.滞后.ToString(),
                        //ZH= yiwu.ZH,
                        ZH = zhTask.Count(),// Area.Trim() == "" ? yiwu.ZH : (Area == "330000000000" ? yiwu.ZH_330000 : (Area == "330700000000" ? yiwu.ZH_330700 : yiwu.ZH_330782)),
                        list = zhTask
                    },
                    YJTask = new
                    {
                        Type = Enm.任务状态.预警.ToString(),
                        YJ = yjTask.Count(), //Area.Trim() == "" ? yiwu.YJ : (Area == "330000000000" ? yiwu.YJ_330000 : (Area == "330700000000" ? yiwu.YJ_330700 : yiwu.YJ_330782)),
                        list = yjTask
                    },
                    ZCTask = new
                    {
                        Type = Enm.任务状态.正常推进.ToString(),
                        ZC = zcTask.Count(),//Area.Trim() == "" ? yiwu.ZC : (Area == "330000000000" ? yiwu.ZC_330000 : (Area == "330700000000" ? yiwu.ZC_330700 : yiwu.ZC_330782)),
                        list = zcTask
                    },
                    WCTask = new
                    {
                        Type = Enm.任务状态.已完成.ToString(),
                        WC = wcTask.Count(),// Area.Trim() == "" ? yiwu.WC : (Area == "330000000000" ? yiwu.WC_330000 : (Area == "330700000000" ? yiwu.WC_330700 : yiwu.WC_330782)),
                        list = wcTask
                    }
                }
            });
        }
        //[HttpPost]
        //获取全景透视工作类别
        [User]
        public IActionResult GetTaskType()
        {
            var year = Form.GetInt("Year");
            var TaskType = Form.GetInt("TaskType", 0);
            if (year == 0) year = 2021;
            var task = ctx.Yqd_Task.Where(it => it.IsShow && it.Year == year + "");
            if (TaskType > 0) task = task.Where(it => ("," + it.TaskType + ",").Contains("," + TaskType + ","));
            var list = task.Select(it => it.TaskPath.Substring(0, it.TaskPath.IndexOf('/'))).Distinct().ToList();
            return this.ToJson(new
            {
                success = true,
                data = list.Select(it => new
                {
                    text = it,
                    value = it
                })
            });
        }

        [User]
        public IActionResult EditTaskType()
        {
            var TaskID = Form.GetLong("TaskID");
            var TaskType = Form.GetString("TaskType");
            var TaskPath = Form.GetString("TaskPath", "");
            var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            task.TaskType = TaskType;
            if (TaskPath != "")
            {
                if (string.IsNullOrWhiteSpace(task.TaskPath)) task.TaskPath = TaskPath;
                else task.TaskPath += ";" + TaskPath.Replace(",", "/");
            }
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        //获取每年分管领导
        [User]
        public IActionResult GetUnitLeader()
        {
            var year = Form.GetInt("Year", 0);
            var data = new List<object>();
            data.Add(new
            {
                text = "全部",
                value = "王健"
            });
            var list = ctx.Yqd_UnitLeader.Where(it => it.Year == year && it.IsShow);
            data.AddRange(list.OrderBy(it => it.Tactic).ToList().Select(it => new
            {
                text = it.Leader,
                value = it.Leader,
                id = it.ID
            }).Distinct()
            );
            return this.ToJson(new
            {
                success = true,
                data
            });
            //if (year > 2021)
            //{
            //}
            //else
            //{
            //    var list = ctx.Yqd_Unit.Where(it => !string.IsNullOrWhiteSpace(it.Leader));
            //    data.AddRange(list.OrderByDescending(it => it.Tactic).ToList().Select(it => new
            //    {
            //        text = it.Leader,
            //        value = it.Leader,
            //        id = it.ID
            //    }).Distinct()
            //    );
            //    return this.ToJson(new
            //    {
            //        success = true,
            //        data
            //    });
            //}
        }

        //[HttpPost]
        //获取当前任务列表的牵头单位列表
        [User]
        public IActionResult GetTaskUnit()
        {
            var y = DateTime.Now.Year;
            var Year = Form.GetInt("Year", 0);
            var TaskTypeID = Form.GetString("TaskTypeID");
            var isLb = Form.GetInt("isLb", 0); //0默认精准督查 1：回头看
            var Status = Form.GetInt("Status", 0);
            var eStatus = Form.GetInt("eStatus", 0);
            var p = Form.GetInt("platform", 0);
            var LeaderUnitCode = Form.GetString("LeaderUnitCode", p == 2 ? WxUser.LogonInfo.UnitCode : "");
            var Leader = Form.GetString("Leader", "王健");
            var AreaCode = Form.GetString("AreaCode");
            var key = Form.GetString("key");
            var EvaluateInfo = Form.GetString("EvaluateInfo");
            var Link = Form.GetString("Link");
            var State = Form.GetInt("State", 0);
            var dstatus = Form.GetInt("dstatus");
            var TaskType = Form.GetString("TaskType", "");
            var where = "";
            string where2 = "SELECT  UnitCode, Name, Tactic FROM Yqd_Unit WHERE  UnitCode in (select LeaderUnitCode from yqd_Task where IsShow = 1";
            if (Status > 0)
            {
                where += Status == 1 ? " and TaskStatus in (-1,1)" : " and TaskStatus={0}";
            }
            if (Year > 0)
            {
                where += " and [Year]=" + Year;
            }
            if (TaskType != "")
            {
                where += " and (','+[TaskType]+',') like {6}";
            }
            if (TaskTypeID != "0")
            {
                where += " and SUBSTRING(TaskPath,1,CHARINDEX('/',TaskPath)-1)={7}";
            }
            if (!string.IsNullOrWhiteSpace(LeaderUnitCode))
            {
                var code = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == LeaderUnitCode)?.OrganizationCode ?? "";
                where += " and ((','+LeaderUnitCode+',') like {1} or LeaderUnitCode='" + code + "')";
            }
            if (!string.IsNullOrWhiteSpace(AreaCode))
            {
                where += " and FAreaCode={2}";
            }
            if (key.Trim() != "")
            {
                where += " and lower(ltrim(rtrim([TaskName]))) like {3}";
            }
            if (EvaluateInfo.Trim() != "" && Status == 3)
            {
                var einfos = new List<long>();
                switch (EvaluateInfo)
                {
                    case "1":
                        var tbls = new[] { "Person", "Task", "QuotaTable", "TaskPlan" };
                        einfos = ctx.Yqd_EvaluateInfo.Where(it => it.TaskStatus == 3 && tbls.Contains(it.DataTable) && it.IsShow).Select(it => it.TaskID).ToList();
                        break;
                    case "2":
                        einfos = ctx.Yqd_EvaluateInfo.Where(it => it.TaskStatus == 3 && it.DataTable == "Quota" && it.IsShow).Select(it => it.TaskID).ToList();
                        break;
                }
                if (einfos.Count > 0)
                {
                    where += " and TaskID in (" + string.Join(",", einfos) + ") ";
                }
            }
            if (State > 0)
            {
                switch (State)
                {
                    case 10:
                        where += " and [TaskID] in(select TaskID from Yqd_Scheme where isDel=0 and ItemType=" + (int)事项类型.精准督查 + " and [CheckStatus]=" + (int)审核状态.待审 + ")";
                        break;
                    case 20:
                        where += " and [TaskID] in(select TaskID from Yqd_PlanProgress where ItemType=" + (int)事项类型.精准督查 + " and [CheckStatus]=" + (int)审核状态.待审 + ")";
                        break;
                    case 30:
                        where += " and [TaskID] in(select TaskID from Yqd_FinishReport where ItemType=" + (int)事项类型.精准督查 + " and [CheckStatus]=" + (int)审核状态.待审 + ")";
                        break;
                    case 40:
                        where += " and ([TaskID] in(select TaskID from Yqd_ExactSupervise where isDel=0 and [Status]=" + (int)任务状态.已完成 + ") or [TaskID] in(select TaskID from Yqd_Supervise where isdel=0 and [SuperviseType]=20 and [Status]=" + (int)任务状态.已完成 + "))";
                        break;
                    case 50:
                        if (eStatus > 0)
                        {
                            where += " and [TaskID] in(select TaskID from Yqd_ExactSupervise where isDel=0 and [islb]=" + isLb + " and [Status]=" + eStatus + "  )";
                        }
                        else
                        {
                            where += " and [TaskID] in(select TaskID from Yqd_ExactSupervise where isDel=0 and [islb]=" + isLb + ")";
                        }

                        break;
                }
            }
            if (dstatus > 0)
            {
                switch (dstatus)
                {
                    case 10:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [SuperviseType]=20 and [Status] in (2,3,4))";
                        break;
                    case 20:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where isdel=0 and [IsRead]=0 and [SuperviseType]=10)";
                        break;
                    case 30:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [SuperviseType]=20 and [Status]=4)";
                        break;
                    case 40:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [SuperviseType]=20 and [Status]=1)";
                        break;
                    case 50:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [SuperviseType]=10)";
                        break;
                    case 60:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [SuperviseType]=20)";
                        break;
                    case 70:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [IsRead]=1 and [SuperviseType]=10)";
                        break;
                }
            }
            if (Link.Trim() != "")
            {
                if (Link == "Yqd_QuotaTable")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 1 ) ";

                }
                else if (Link == "Yqd_QuotaMsg")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaMsg Where IsShow = 1 ) ";
                }
                else if (Link == "Yqd_Supervise_10")
                {
                    where += " and TaskID in (Select TaskID From Yqd_Supervise Where  isdel=0 and SuperviseType = 10 ) ";
                }
                else if (Link == "Yqd_Supervise_20")
                {
                    where += " and TaskID in (Select TaskID From Yqd_Supervise Where  isdel=0 and SuperviseType = 20 ) ";
                }
                else if (Link == "Yqd_QuotaPlan")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 2 ) ";
                }
                else
                {
                    where += " and TaskID in (Select TaskID From  " + Link + "  ) ";
                }
            }

            string sql2 = where;
            if (Leader != "王健")
            {
                //where += " and ((LeaderUnitCode in (Select UnitCode From Yqd_Unit Where Leader={4})) or ConnectMan={4})";
                where += " and ((LeaderUnitCode in (Select substring(a.unit,b.number,charindex(',',a.unit+',',b.number)-b.number) From Yqd_UnitLeader a inner join master.dbo.spt_values b on b.number between 1 and len(a.unit) Where a.Leader like '%" + Leader + "%' and a.unit !='' " + (Year > 0 ? " and year=" + Year : "") + ")) or ConnectMan={4})";
                sql2 += " and ((UnitCode in (Select substring(a.unit,b.number,charindex(',',a.unit+',',b.number)-b.number) From Yqd_UnitLeader a inner join master.dbo.spt_values b on b.number between 1 and len(a.unit) Where a.Leader like '%" + Leader + "%' and a.unit !='' " + (Year > 0 ? " and year=" + Year : "") + ")) or ConnectMan={4})";
            }
            string sql = where2 + where + " ) or OrganizationCode in (select LeaderUnitCode from yqd_Task where IsShow = 1 " + sql2 + ") ORDER BY Tactic";
            var list = ctx.Database.SqlQuery<Unit>(sql, Status, "%," + LeaderUnitCode + ",%", AreaCode, "%" + key.ToLower().Trim() + "%", Leader, Year, "%," + TaskType + ",%", TaskTypeID);
            // var Tist = ctx.Database.SqlPager<Yqd_Task>((cp - 1) * size, size, "*", where, "[CreateTime] desc,ID desc",);
            return this.ToJson(new
            {
                success = true,
                data = list,
                sql = sql
            });

            //var TaskTypeID = Form.GetLong("TaskTypeID");
            //var TaskType = Form.GetString("TaskType", "");
            //var Status = Form.GetInt("Status", 0);
            //var AreaCode = Form.GetString("AreaCode");
            //var key = Form.GetString("key");
            //var year = Form.GetInt("Year",0);
            //var Leader = Form.GetString("Leader", "王健");
            //var Link = Form.GetString("Link");

            //var EvaluateInfo = Form.GetString("EvaluateInfo");

            //var where = "SELECT  UnitCode, Name, Tactic FROM Yqd_Unit WHERE  UnitCode in (select LeaderUnitCode from yqd_Task where IsShow = 1";
            //if (Status > 0)
            //{
            //    where += " and [TaskStatus] = {0}";
            //}


            //if (!string.IsNullOrWhiteSpace(AreaCode))
            //{
            //    where += " and [FAreaCode]={1}";
            //}

            //if (key.Trim() != "")
            //{
            //    where += " and lower(ltrim(rtrim([TaskName]))) like {2}";
            //}

            //if (Leader != "王健")
            //{
            //    where += " and  Leader={3}";
            //}

            //if (year > 0)
            //{
            //    where += " and [Year]={4}";
            //}
            //if (TaskType != "")
            //{
            //    where += " and (','+[TaskType]+',') like {5}";
            //}

            //if (EvaluateInfo.Trim() != "" && Status == 3)
            //{
            //    var einfos = new List<long>();
            //    switch (EvaluateInfo)
            //    {
            //        case "1":
            //            var tbls = new[] { "Person", "Task", "QuotaTable", "TaskPlan" };
            //            einfos = ctx.Yqd_EvaluateInfo.Where(it => it.TaskStatus == 3 && tbls.Contains(it.DataTable) && it.IsShow).Select(it => it.TaskID).ToList();
            //            break;
            //        case "2":
            //            einfos = ctx.Yqd_EvaluateInfo.Where(it => it.TaskStatus == 3 && it.DataTable == "Quota" && it.IsShow).Select(it => it.TaskID).ToList();
            //            break;
            //    }
            //    if (einfos.Count > 0)
            //    {
            //        where += " and TaskID in (" + string.Join(",", einfos) + ") ";
            //    }

            //}


            //if (Link.Trim() != "")
            //{
            //    if (Link == "Yqd_QuotaTable")
            //    {
            //        where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 1 ) ";

            //    }
            //    else if (Link == "Yqd_QuotaMsg")
            //    {
            //        where += " and TaskID in (Select TaskID From Yqd_QuotaMsg Where IsShow = 1 ) ";
            //    }
            //    else if (Link == "Yqd_QuotaPlan")
            //    {
            //        where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 2 ) ";
            //    }
            //    else
            //    {
            //        where += " and TaskID in (Select TaskID From " + Link + "  ) ";
            //    }

            //}


            //if (TaskTypeID > 0)
            //{
            //    var TaskTypeIDs = ctx.Yqd_TaskType.Where(it => it.ParentID == TaskTypeID).Select(it => it.TypeID).ToArray();
            //    var sql = "";
            //    where += " and (";

            //    foreach (var id in TaskTypeIDs)
            //    {
            //        sql += (string.IsNullOrEmpty(sql) ? "" : " or ") + "  TaskIDPath like '%" + id + "%' ";

            //    }
            //    where += sql;
            //    where += " )";
            //}
            //where += " ) ORDER BY Tactic";
            //  var list = ctx.Database.SqlQuery<Unit>(where, Status, AreaCode, "%" + key.ToLower().Trim() + "%", Leader, year, "%," + TaskType + ",%");

            //return this.ToJson(new
            //{
            //    success = true,
            //    data = list
            //});
        }
        //[HttpPost]
        //获取当前任务列表
        [User]
        public IActionResult GetTaskList()
        {
            //已完成 = 1,
            //正常推进 = 2,
            //预警 = 3,
            //滞后 = 4
            var y = DateTime.Now.Year;
            var Year = Form.GetInt("Year", 0);
            var TaskTypeID = Form.GetString("TaskTypeID");
            var isLb = Form.GetInt("isLb", 0); //0默认精准督查 1：回头看
            var TaskStatus = Form.GetInt("TaskStatus", 0);//督查任务状态：0默认全部 、2正常推进、1已完成、3预警、4滞后
            var Status = Form.GetInt("Status", 0);//办理情况的任务状态：0默认全部 、2正常推进、1已完成、3预警、4滞后
            var eStatus = Form.GetInt("eStatus", 0);//审核状态 0默认全部、 1:待审 2：同意 3：退回
            var platform = Form.GetInt("platform", 0);
            var LeaderUnitCode = Form.GetString("LeaderUnitCode", platform == 2 ? WxUser.LogonInfo.UnitCode : "");
            var Leader = Form.GetString("Leader", "王健");
            var AreaCode = Form.GetString("AreaCode");
            var key = Form.GetString("key");
            var cp = Form.GetInt("cp", 1);
            var size = Form.GetInt("size", 10);
            var EvaluateInfo = Form.GetString("EvaluateInfo");
            var Link = Form.GetString("Link");
            var State = Form.GetInt("State", 0);//左侧导航 10工作方案  20进展反馈 30 办结报告 50任务列表
            var dstatus = Form.GetInt("dstatus");
            var TaskType = Form.GetString("TaskType", "");
            var isAssign = Form.GetString("isAssign");//是否交办 默认全部 0：未交办 1：已交办
            if (cp < 1)
            {
                cp = 1;
            }
            var where = " IsShow =1 ";
            //是否交办
            if (!string.IsNullOrEmpty(isAssign))
            {
                if (isAssign == "1")
                {
                    where += " and TaskId in (select TaskId from [dbo].[Yqd_Assign] where ItemType=" + (int)事项类型.精准督查 + " and ItemID in (select SuperviseID from Yqd_ExactSupervise where isDel=0 and [islb]=" + isLb + ")) ";
                }
                else if (isAssign == "0")
                {
                    where += " and TaskId not in (select TaskId from [dbo].[Yqd_Assign] where ItemType=" + (int)事项类型.精准督查 + " and ItemID in (select SuperviseID from Yqd_ExactSupervise where isDel=0 and [islb]=" + isLb + ")) ";
                }
            }
            if (TaskStatus > 0)
            {
                where += TaskStatus == 1 ? " and TaskStatus in (-1,1)" : " and TaskStatus=" + TaskStatus;
            }
            if (TaskType != "")
            {
                where += " and (','+[TaskType]+',') like '%," + TaskType + ",%'";
            }
            if (TaskTypeID != "0")
            {
                where += " and SUBSTRING(TaskPath,1,CHARINDEX('/',TaskPath)-1)='" + TaskTypeID + "'";
            }
            if (!string.IsNullOrWhiteSpace(LeaderUnitCode))
            {
                var code = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == LeaderUnitCode)?.OrganizationCode ?? "";
                where += " and ((','+LeaderUnitCode+',') like '%," + LeaderUnitCode + ",%' or LeaderUnitCode='" + code + "')";
            }

            if (!string.IsNullOrWhiteSpace(AreaCode))
            {
                where += " and FAreaCode=" + AreaCode;
            }


            if (key.Trim() != "")
            {
                where += " and lower(ltrim(rtrim([TaskName]))) like '%" + key.ToLower().Trim() + "%'";
            }
            if (Leader != "王健")
            {
                where += $@" and (
LeaderUnitCode in (
select OrganizationCode from Yqd_Unit where UnitCode in (Select substring(a.unit, b.number, charindex(',', a.unit + ',', b.number) - b.number) From Yqd_UnitLeader a inner join master.dbo.spt_values b on b.number between 1 and len(a.unit) Where a.Leader = '{Leader}' and a.unit != '' {(Year > 0 ? " and a.year=" + Year : "")} or ConnectMan = '{Leader}'))
or
LeaderUnitCode in (
select UnitCode from Yqd_Unit where UnitCode in (Select substring(a.unit, b.number, charindex(',', a.unit + ',', b.number) - b.number) From Yqd_UnitLeader a inner join master.dbo.spt_values b on b.number between 1 and len(a.unit) Where a.Leader = '{Leader}' and a.unit != ''{(Year > 0 ? " and a.year=" + Year : "")} or ConnectMan = '{Leader}'))
)";
            }
            if (EvaluateInfo.Trim() != "" && Status == 3)
            {
                var einfos = new List<long>();
                switch (EvaluateInfo)
                {
                    case "1":
                        var tbls = new[] { "Person", "Task", "QuotaTable", "TaskPlan" };
                        einfos = ctx.Yqd_EvaluateInfo.Where(it => it.TaskStatus == 3 && tbls.Contains(it.DataTable) && it.IsShow).Select(it => it.TaskID).ToList();
                        break;
                    case "2":
                        einfos = ctx.Yqd_EvaluateInfo.Where(it => it.TaskStatus == 3 && it.DataTable == "Quota" && it.IsShow).Select(it => it.TaskID).ToList();
                        break;
                }
                if (einfos.Count > 0)
                {
                    where += " and TaskID in (" + string.Join(",", einfos) + ") ";
                }

            }
            //string sql2 = "";
            //if (eStatus > 0)
            //{
            //    sql2 = " and [Status]=" + eStatus;
            //}

            if (dstatus > 0)
            {
                switch (dstatus)
                {
                    case 10:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [SuperviseType]=20 and [Status] in (2,3,4))";
                        break;
                    case 20:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [IsRead]=0 and [SuperviseType]=10)";
                        break;
                    case 30:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [SuperviseType]=20 and [Status]=4)";
                        break;
                    case 40:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [SuperviseType]=20 and [Status]=1)";
                        break;
                    case 50:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [SuperviseType]=10)";
                        break;
                    case 60:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [SuperviseType]=20)";
                        break;
                    case 70:
                        where += " and TaskID in (select TaskID from Yqd_Supervise where  isdel=0 and [IsRead]=1 and [SuperviseType]=10)";
                        break;
                }
            }
            if (Link.Trim() != "")
            {
                if (Link == "Yqd_QuotaTable")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 1 ) ";

                }
                else if (Link == "Yqd_QuotaMsg")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaMsg Where IsShow = 1 ) ";
                }
                else if (Link == "Yqd_Supervise_10")
                {
                    where += " and TaskID in (Select TaskID From Yqd_Supervise Where  isdel=0 and SuperviseType = 10 ) ";
                }
                else if (Link == "Yqd_Supervise_20")
                {
                    where += " and TaskID in (Select TaskID From Yqd_Supervise Where  isdel=0 and SuperviseType = 20 ) ";
                }
                else if (Link == "Yqd_QuotaPlan")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 2 ) ";
                }
                else
                {
                    where += " and TaskID in (Select TaskID From  " + Link + "  ) ";
                }
            }
            //左侧导航
            int waitTotalcount = 0;
            if (State > 0)
            {
                switch (State)
                {
                    case 10:
                        where += " and [TaskID] in(select TaskID from Yqd_Scheme where isDel=0 " + (Year > 0 ? $" and year(Instime)={Year}" : "") + " and ItemType=" + (int)事项类型.精准督查 + " and [CheckStatus]=" + (int)审核状态.待审 + " and [ItemID] in(select SuperviseID from Yqd_ExactSupervise where isDel=0 and [islb]=" + isLb + (Status > 0 ? " and Status=" + Status : " and Status in (2,3,4)") + "  ))  ";

                        //where += " and [TaskID] in(select TaskID from Yqd_Scheme where isDel=0 and ItemType=" + (int)事项类型.精准督查 + (eStatus > 0 ? " and [CheckStatus]=" + eStatus : "") + " and [ItemID] in(select SuperviseID from Yqd_ExactSupervise where isDel=0 and [islb]=" + isLb + (Status > 0 ? " and Status=" + Status : "") + "  ))  ";

                        waitTotalcount = ctx.Database.SqlQuery<int>("select count(distinct TaskID) from Yqd_ExactSupervise where isDel=0 and [SuperviseID] in(select ItemID from Yqd_Scheme where isDel=0 " + (Year > 0 ? $" and year(Instime)={Year}" : "") + " and ItemType={0} and [CheckStatus]={1} and TaskID in (select TaskID from Yqd_Task where " + where + ")) and islb={2}", (int)事项类型.精准督查, (int)审核状态.待审, isLb).First();
                        break;
                    case 20:
                        where += " and [TaskID] in(select TaskID from Yqd_PlanProgress where " + (eStatus == 1 ? "AuditStatus=0 and" : "") + " isDel=0 " + (Year > 0 ? $" and year(Instime)={Year}" : "") + " and ItemType=" + (int)事项类型.精准督查 + " and [CheckStatus]=" + (int)审核状态.待审 + " and [ItemID] in(select SuperviseID from Yqd_ExactSupervise where isDel=0 and [islb]=" + isLb + (Status > 0 ? " and Status=" + Status : " and Status in (2,3,4)") + " ))  ";

                        //where += " and [TaskID] in(select TaskID from Yqd_PlanProgress where isDel=0 and ItemType=" + (int)事项类型.精准督查 + (eStatus > 0 ? " and [CheckStatus]=" + eStatus : "") + " and [ItemID] in(select SuperviseID from Yqd_ExactSupervise where isDel=0 and [islb]=" + isLb + (Status > 0 ? " and Status=" + Status : "") + "  ) ) ";

                        waitTotalcount = ctx.Database.SqlQuery<int>("select count(distinct TaskID) from Yqd_ExactSupervise where isDel=0 and [SuperviseID] in(select ItemID from Yqd_PlanProgress where isDel=0 " + (Year > 0 ? $" and year(Instime)={Year}" : "") + " and ItemType={0} and [CheckStatus]={1} and AuditStatus=0 and TaskID in (select TaskID from Yqd_Task where  " + where + ")) and islb={2}", (int)事项类型.精准督查, (int)审核状态.待审, isLb).First();

                        break;
                    case 30:

                        where += " and [TaskID] in(select TaskID from Yqd_FinishReport where isDel=0 " + (Year > 0 ? $" and year(Instime)={Year}" : "") + " and ItemType=" + (int)事项类型.精准督查 + " and [CheckStatus]=" + (int)审核状态.待审 + " and [ItemID] in(select SuperviseID from Yqd_ExactSupervise where isDel=0 and [islb]=" + isLb + (Status > 0 ? " and Status=" + Status : " ") + "  ))  ";

                        //where += " and [TaskID] in(select TaskID from Yqd_FinishReport where isDel=0 and ItemType=" + (int)事项类型.精准督查 + (eStatus > 0 ? " and [CheckStatus]=" + eStatus : "") + " and [ItemID] in(select SuperviseID from Yqd_ExactSupervise where isDel=0 and [islb]=" + isLb + (Status > 0 ? " and Status=" + Status : "") + "  ) )";
                        waitTotalcount = ctx.Database.SqlQuery<int>("select count(distinct TaskID) from Yqd_ExactSupervise where isDel=0 and [SuperviseID] in(select ItemID from Yqd_FinishReport where isDel=0 " + (Year > 0 ? $" and year(Instime)={Year}" : "") + " and ItemType={0} and [CheckStatus]={1} and TaskID in (select TaskID from Yqd_Task where  " + where + ")) and islb={2}", (int)事项类型.精准督查, (int)审核状态.待审, isLb).First();
                        break;
                    case 40:
                        where += " and ([TaskID] in(select TaskID from Yqd_ExactSupervise where isDel=0 " + (Year > 0 ? $" and year(Instime)={Year}" : "") + " and [islb]=" + isLb + " and [Status]=" + (int)任务状态.已完成 + ") or [TaskID] in(select TaskID from Yqd_Supervise where isdel=0 and [SuperviseType]=20 and [Status]=" + (int)任务状态.已完成 + "))";
                        break;
                    case 50:

                        where += " and [TaskID] in(select TaskID from Yqd_ExactSupervise where isDel=0 " + (Year > 0 ? $" and year(Instime)={Year}" : "") + " and [islb]=" + isLb + (Status > 0 ? " and Status=" + Status : "") + " ) ";

                        break;
                }

                if (Year > 0)
                {
                    where += " and [Year]=" + Year;
                }
            }
            else
            {
                if (Year > 0)
                {
                    where += " and year=" + Year + " ";
                }
            }
            string orderBy = "";
            string dateSql = "";
            if (platform == 1)//治理端
            {
                if (Year == 2021)
                {
                    dateSql = ",(select max(updatatime) from [dbo].[Yqd_Quota] where TaskID=Yqd_Task.TaskID) as updatatime";
                }
                else
                {
                    dateSql = ",(select max(updatatime) from [dbo].[Yqd_QuotaNew] where TaskID=Yqd_Task.TaskID) as updatatime";
                }
                orderBy = "[updatatime] desc,";
            }
            else if (platform == 3)// 督查备选
            {
                dateSql = ",(select max(Instime) from [dbo].[Yqd_Assign] where TaskID=Yqd_Task.TaskID and ItemType=" + (int)事项类型.精准督查 + " and ItemID in (select SuperviseID from Yqd_ExactSupervise where isDel=0 and [islb]=" + isLb + " )) as AssignTime";
                orderBy = "[AssignTime] desc,";
            }
            //分组获取部门
            var listUnit = ctx.Database.SqlQuery<Yqd_Task>("select * From Yqd_Task where " + where).GroupBy(x => x.LeaderUnitCode).Select(x => x.Key.ToString()).ToList();

            var (totalcount, data) = ctx.Database.SqlPager<Yqd_Task>((cp - 1) * size, size, "*" + dateSql, where, orderBy + "ID desc");

            var totalPages = totalcount != 0 ? (totalcount % size) == 0 ? (totalcount / size) : (totalcount / size) + 1 : 0;

            var taskid = data.Select(it => it.TaskID).ToList();
            var ys = ctx.Yqd_Supervise.Where(it => it.IsDel == 0 && taskid.Contains(it.TaskID)).ToList();
            var dc = ctx.Yqd_ExactSupervise.Where(it => taskid.Contains(it.TaskID)).ToList();
            var r = WxUser.LogonInfo.Role;
            //var tasids = data.Select(it => it.TaskID).ToList();
            //var  qlist= ctx.Yqd_Quota.Where(it => tasids.Contains(it.TaskID)  && it.IsShow).OrderByDescending(it=>it.CreateTime).ToList();
            var Unitcode = data.Select(it => it.LeaderUnitCode).ToList().Distinct();
            var unitList = ctx.Yqd_Unit.Where(it => Unitcode.Contains(it.UnitCode) || Unitcode.Contains(it.OrganizationCode)).ToList();
            var ztList = new List<dynamic>();
            var TaskIDs = data.Select(it => it.TaskID).ToList();
            List<Yqd_ExactSupervise> es = new List<Yqd_ExactSupervise>();
            if (isLb == 0)
            {
                es = ctx.Yqd_ExactSupervise.Where(it => !it.IsDel && TaskIDs.Contains(it.TaskID) && !it.IsLb).ToList();
            }
            else
            {
                es = ctx.Yqd_ExactSupervise.Where(it => !it.IsDel && TaskIDs.Contains(it.TaskID) && it.IsLb).ToList();
            }
            return this.ToJson(new
            {
                success = true,
                totalcount,
                totalPages,
                waitTotalcount,
                sql = where,
                unitList = ctx.Yqd_Unit.Where(it => listUnit.Contains(it.UnitCode)).ToList(),
                IsAdmin = r.Any(it => it == 角色类型.管理员),
                data = data.Select(m => new
                {
                    ID = m.ID.ToString(),
                    TaskID = m.TaskID.ToString(),
                    m.TaskName,
                    m.FAreaCode,
                    //UpdateTime = qlist.FirstOrDefault(it=>it.TaskID==m.TaskID)?.CreateTime.ToString("yyyy-MM-dd"),// m.UpdateTime.ToString("yyyy-MM-dd"),
                    //UpdateTime = m.UpdateTime.ToString("yyyy-MM-dd"),
                    UpdateTime = Year == 2021 ? ctx.Yqd_Quota.Where(x => x.TaskID == m.TaskID).OrderByDescending(x => x.UpdataTime).FirstOrDefault()?.UpdataTime?.ToString("yyyy-MM-dd") : ctx.Yqd_QuotaNew.Where(x => x.TaskID == m.TaskID).OrderByDescending(x => x.UpdataTime).FirstOrDefault() != null ? ctx.Yqd_QuotaNew.Where(x => x.TaskID == m.TaskID).OrderByDescending(x => x.UpdataTime).FirstOrDefault()?.UpdataTime?.ToString("yyyy-MM-dd") : m.UpdateTime.ToString("yyyy-MM-dd"),
                    CreateTime = m.CreateTime.ToString("yyyy-MM-dd"),
                    TaskPath = m.TaskPath.Split("/")[0],
                    IsYear = m.Year == y.ToString(),
                    isDB = ys.Any(it => it.TaskID == m.TaskID && it.SuperviseType == 督导类型.钉办),
                    isDD = ys.Any(it => it.TaskID == m.TaskID && it.SuperviseType == 督导类型.督导),
                    isDC = dc.Any(it => it.TaskID == m.TaskID),
                    LeaderUnitName = unitList.FirstOrDefault(it => it.UnitCode == m.LeaderUnitCode || it.OrganizationCode == m.LeaderUnitCode)?.Name,
                    //  m.LeaderUnitName,
                    m.TaskStatus,
                    LeadUnitCode = m.LeaderUnitCode,
                    Status = es.FirstOrDefault(it => it.TaskID == m.TaskID)?.Status.ToString(),
                    SuperviseID = es.FirstOrDefault(it => it.TaskID == m.TaskID)?.SuperviseID,
                    AssignTime = es.FirstOrDefault(it => it.TaskID == m.TaskID) == null ? "" : ctx.Yqd_Assign.FirstOrDefault(it => it.TaskID == m.TaskID && it.ItemID == es.FirstOrDefault(x => x.TaskID == m.TaskID).SuperviseID && it.ItemType == 事项类型.精准督查)?.Instime.ToString("yyyy-MM-dd")
                    //SchemeID = schemList.Any() ? schemList.Where(x => x.ItemID == es.FirstOrDefault(it => it.TaskID == m.TaskID)?.SuperviseID).FirstOrDefault()?.SchemeID : 0,
                    //ProgressID = planList.Any() ? planList.Where(x => x.ItemID == es.FirstOrDefault(it => it.TaskID == m.TaskID)?.SuperviseID).FirstOrDefault()?.ProgressID : 0,
                    //ReportID = finishList.Any() ? finishList.Where(x => x.ItemID == es.FirstOrDefault(it => it.TaskID == m.TaskID)?.SuperviseID).FirstOrDefault()?.ReportID : 0
                }).ToList()
            });
        }

        //[HttpPost]
        //获取任务统计
        [User]
        public IActionResult GetTaskStatusTJ()
        {
            var TaskTypeID = Form.GetString("TaskTypeID");
            var TaskType = Form.GetString("TaskType");
            var Year = Form.GetInt("Year", 0);
            var Status = Form.GetInt("Status", 0);
            var p = Form.GetInt("platform", 0);//1.治理 2;工作段 3：督查端
            var LeaderUnitCode = Form.GetString("LeaderUnitCode", p == 2 ? WxUser.LogonInfo.UnitCode : "");
            //var LeaderUnitCode = Form.GetString("LeaderUnitCode");
            var key = Form.GetString("key");
            var Leader = Form.GetString("Leader", "王健");
            var EvaluateInfo = Form.GetString("EvaluateInfo");
            var AreaCode = Form.GetString("AreaCode");
            var Link = Form.GetString("Link");



            var where = "SELECT   TaskStatus, COUNT(*) AS Num FROM Yqd_Task WHERE IsShow = 1";
            if (Status > 0)
            {
                where += Status == 1 ? " and TaskStatus in (-1,1)" : " and TaskStatus={0}";
            }
            if (Year > 0)
            {
                where += " and [Year] = {5}";
            }
            if (TaskTypeID != "0")
            {
                where += " and [TaskPath] like '%" + TaskTypeID + "%'";
            }
            if (TaskType != "")
            {
                where += " and (','+[TaskType]+',') like {7}";
            }
            if (!string.IsNullOrWhiteSpace(LeaderUnitCode))
            {
                var code = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == LeaderUnitCode)?.OrganizationCode ?? "";
                where += " and ((','+LeaderUnitCode+',') like {1} or LeaderUnitCode='" + code + "')";
            }

            if (!string.IsNullOrWhiteSpace(AreaCode))
            {
                where += " and FAreaCode={2}";
            }

            if (key.Trim() != "")
            {
                where += " and lower(ltrim(rtrim([TaskName]))) like {3}";
            }
            if (Leader != "王健")
            {
                where += $@" and (
LeaderUnitCode in (
select OrganizationCode from Yqd_Unit where UnitCode in (Select substring(a.unit, b.number, charindex(',', a.unit + ',', b.number) - b.number) From Yqd_UnitLeader a inner join master.dbo.spt_values b on b.number between 1 and len(a.unit) Where a.Leader = '{Leader}' and a.unit != '' {(Year > 0 ? " and a.year=" + Year : "")} or ConnectMan = '{Leader}'))
or
LeaderUnitCode in (
select UnitCode from Yqd_Unit where UnitCode in (Select substring(a.unit, b.number, charindex(',', a.unit + ',', b.number) - b.number) From Yqd_UnitLeader a inner join master.dbo.spt_values b on b.number between 1 and len(a.unit) Where a.Leader = '{Leader}' and a.unit != '' {(Year > 0 ? " and a.year=" + Year : "")} or ConnectMan = '{Leader}'))
)";
            }

            //if (Leader != "王健")
            //{
            //    where += " and ((LeaderUnitCode in (Select substring(a.unit,b.number,charindex(',',a.unit+',',b.number)-b.number) From Yqd_UnitLeader a inner join master.dbo.spt_values b on b.number between 1 and len(a.unit) Where a.Leader like '%" + Leader + "%' and a.unit !='' )) or ConnectMan={4})";

            //    //if (Year > 2021)
            //    //{
            //    //    where += " and SUBSTRING(TaskPath,1,CHARINDEX('/',TaskPath)-1) in (Select TaskPath From Yqd_UnitLeader Where Leader={4} and [Year]={5})";
            //    //}
            //    //else
            //    //{
            //    //    where += " and LeaderUnitCode in (Select UnitCode From Yqd_Unit Where Leader={4})";
            //    //}
            //}

            if (Link.Trim() != "")
            {
                if (Link == "Yqd_QuotaTable")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 1 ) ";

                }
                else if (Link == "Yqd_QuotaMsg")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaMsg Where IsShow = 1 ) ";
                }
                else if (Link == "Yqd_QuotaPlan")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 2 ) ";
                }
                else
                {
                    where += " and TaskID in (Select TaskID From " + Link + "  ) ";
                }

            }
            if (EvaluateInfo.Trim() != "" && Status == 3)
            {
                var einfos = new List<long>();
                switch (EvaluateInfo)
                {
                    case "1":
                        var tbls = new[] { "Person", "Task", "QuotaTable", "TaskPlan" };
                        einfos = ctx.Yqd_EvaluateInfo.Where(it => it.TaskStatus == 3 && tbls.Contains(it.DataTable) && it.IsShow).Select(it => it.TaskID).ToList();
                        break;
                    case "2":
                        einfos = ctx.Yqd_EvaluateInfo.Where(it => it.TaskStatus == 3 && it.DataTable == "Quota" && it.IsShow).Select(it => it.TaskID).ToList();
                        break;
                }
                if (einfos.Count > 0)
                {
                    where += " and TaskID in (" + string.Join(",", einfos) + ") ";
                }

            }

            where += " GROUP BY TaskStatus";
            where += " ORDER BY TaskStatus";
            var list = ctx.Database.SqlQuery<TaskStatusTJ>(where, Status, "%," + LeaderUnitCode + ",%", AreaCode, "%" + key.ToLower().Trim() + "%", Leader, Year, "%" + TaskTypeID + "%", "%," + TaskType + ",%").ToList();
            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    Count = list.Sum(it => it.Num),
                    WC = list.FirstOrDefault(it => it.TaskStatus == (int)Enm.任务状态.已完成)?.Num ?? 0,
                    ZC = list.FirstOrDefault(it => it.TaskStatus == (int)Enm.任务状态.正常推进)?.Num ?? 0,
                    YJ = list.FirstOrDefault(it => it.TaskStatus == (int)Enm.任务状态.预警)?.Num ?? 0,
                    ZH = list.FirstOrDefault(it => it.TaskStatus == (int)Enm.任务状态.滞后)?.Num ?? 0,

                }
            });
        }
        //[HttpPost]    
        //获取任务概况
        [User]
        public IActionResult GetTaskInfo()
        {
            var TaskID = Form.GetLong("TaskID");
            var Task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            if (Task == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "任务不存在"
                });
            }
            //var P = ctx.Yqd_Person.FirstOrDefault(it=>it.TaskID==TaskID&& it.PersonType==5&&it.IsShow);
            //// 3任务维护员 5分管领导 6部门联络员
            //var W = ctx.Yqd_Person.FirstOrDefault(it => it.TaskID == TaskID && it.PersonType == 3 && it.IsShow);
            //var L = ctx.Yqd_Person.FirstOrDefault(it => it.TaskID == TaskID && it.PersonType == 6 && it.IsShow);
            var P = ctx.Yqd_Person.FirstOrDefault(it => it.TaskID == TaskID && it.PersonType == 5);
            // 3任务维护员 5分管领导 6部门联络员
            var W = ctx.Yqd_Person.FirstOrDefault(it => it.TaskID == TaskID && it.PersonType == 3);
            var L = ctx.Yqd_Person.FirstOrDefault(it => it.TaskID == TaskID && it.PersonType == 6);
            var EResult = ctx.Yqd_EvaluateInfo.Where(it => it.TaskID == TaskID && it.IsShow && it.TaskStatus > 2).Select(it => new
            {
                TaskStatusName = Enum.GetName(typeof(任务状态), it.TaskStatus),
                it.TaskStatus,
                it.TFieldName,
                it.Evaluate,
            }).ToList();
            var ys = ctx.Yqd_Supervise.Where(it => it.IsDel == 0 && it.TaskID == TaskID).ToList();
            var TaskType = "";
            var tps = new List<string>();
            if (!string.IsNullOrWhiteSpace(Task.TaskType))
            {
                var ids = Task.TaskType.Split(",");
                tps.AddRange(ids);
                foreach (var id in ids)
                {
                    if (TaskType != "") TaskType += "&";
                    TaskType += Enum.GetName(typeof(任务类型), int.Parse(id));
                }
            }
            var paths = new List<string>();
            if (!string.IsNullOrWhiteSpace(Task.TaskPath))
            {
                var pt = Task.TaskPath.Split(";");
                foreach (var p in pt)
                {
                    paths.Add(p.Split("/")[0]);
                }
            }
            var TaskPath = Task.TaskPath;
            if (!string.IsNullOrWhiteSpace(TaskPath))
            {
                TaskPath = string.Join('/', (TaskPath.Split(";").Distinct()));
                TaskPath = string.Join('/', (TaskPath.Split("/").Distinct()));
            }
            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    Task.TaskName,
                    Task.LeaderUnitName,
                    Task.ReformTarget,
                    TaskPath,
                    Task.TaskStatus,
                    Task.Year,
                    TaskType,
                    tps = tps.Distinct(),
                    paths = paths.Distinct(),
                    Leader = P?.PersonName,
                    Weihu = W?.PersonName,
                    Lianluo = L?.PersonName,
                    isDB = ys.Any(it => it.SuperviseType == 督导类型.钉办),
                    isDD = ys.Any(it => it.SuperviseType == 督导类型.督导),
                    ErrorId = ctx.Yqd_TaskError.FirstOrDefault(it => it.TaskID == Task.TaskID)?.ID ?? 0,
                    //  isError = ctx.Yqd_Supervise.Any(it => it.TaskID == Task.TaskID),
                    TaskStatusName = Enum.GetName(typeof(任务状态), Task.TaskStatus),
                    EResult,
                }
            });
        }

        [User]
        public IActionResult GetTaskTitle()
        {
            var TaskID = Form.GetLong("TaskID");
            var Task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            if (Task == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "任务不存在"
                });
            }
            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    Task.TaskName
                }
            });
        }
        //[HttpPost]
        //获取任务指标
        [User]
        public IActionResult GetTaskQuota()
        {
            var TaskID = Form.GetLong("TaskID");
            var QuotaList = ctx.Yqd_QuotaNew.Where(it => it.TaskID == TaskID && it.IsShow).ToList();
            var Milestone = ctx.Yqd_Milestone.Where(it => it.TaskID == TaskID && it.IsShow).ToList();
            var qml = ctx.Yqd_QuotaMsg.Where(it => it.TaskID == TaskID && it.IsShow).ToList();
            var arr = new ArrayList();
            foreach (var Q in QuotaList)
            {
                var qm = Milestone.Where(it => it.TaskQuotaCode == Q.QuotaCode).OrderBy(it => it.MilestoneTime).ToList();
                arr.Add(new
                {
                    Q.QuotaName,
                    Q.QuotaCode,
                    Q.ValueUnit,
                    Q.QuotaType,
                    Q.ValueType,
                    Q.StartValue,
                    Q.CurrentValue,
                    Q.TargetValue,
                    Q.Calucation,
                    UpdataTime = Q.UpdataTime == null ? "" : Q.UpdataTime?.ToString("yyyy-MM-dd"),
                    Q.ds,
                    MList = qm.Select(it => new
                    {
                        it.MilestoneTime,
                        it.TargetValue,
                        MT = it.MilestoneTime.ToString("M月")
                    }),
                    IsMsg = qml.Any(it => it.QuotaCode == Q.QuotaCode && it.IsShow)
                });
            }
            return this.ToJson(new
            {
                success = true,
                data = arr
            });
        }

        //[HttpPost]
        //获取工作计划
        [User]
        public IActionResult GetTaskPlan()
        {
            var TaskID = Form.GetLong("TaskID");
            var PlanList = ctx.Yqd_TaskPlan.Where(it => it.TaskID == TaskID && it.IsShow).OrderBy(it => it.EndTime).ToList();
            var arr = new ArrayList();
            foreach (var p in PlanList)
            {
                arr.Add(new
                {
                    p.MilestoneTime,
                    p.PlanName,
                    p.CompleteDesc,
                    p.PlanStatus
                });
            }
            return this.ToJson(new
            {
                success = true,
                data = arr
            });
        }

        //[HttpPost]
        //获取指标预警提醒
        [User]
        public IActionResult GetQuotaMsg()
        {
            var QuotaCode = Form.GetString("QuotaCode");
            var qmlist = ctx.Yqd_QuotaMsg.Where(it => it.QuotaCode == QuotaCode && it.IsShow).ToList();
            var arr = new ArrayList();
            foreach (var qm in qmlist)
            {
                arr.Add(new
                {
                    qm.ds,
                    qm.Msg
                });
            }
            return this.ToJson(new
            {
                success = true,
                data = arr
            });
        }


        [User]
        public IActionResult GetQuotaFieldList()
        {
            var list = ctx.Yqd_QuotaField.ToList();

            var arr = new ArrayList();

            foreach (var f in list)
            {
                arr.Add(new
                {
                    Fname = f.FieldName,
                    Fid = f.FieldID
                });
            }
            return this.ToJson(new
            {
                success = true,
                data = arr
            });
        }
        [User]
        public IActionResult AddQuotaTable()
        {
            var QuotaCode = Form.GetString("QuotaCode");
            var FieldIDs = Form.GetString("FieldIDs");
            var TableID = Form.GetInt("TableID");
            var Quota = ctx.Yqd_Quota.FirstOrDefault(it => it.QuotaCode == QuotaCode && it.IsShow);
            if (Quota == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "指标信息不存在"
                });
            }

            var table = ctx.Yqd_QuotaTable.FirstOrDefault(it => it.TableID == TableID);
            if (table == null)
            {
                var model = new Yqd_QuotaTable();
                model.TaskID = Quota.TaskID;
                model.QuotaCode = Quota.QuotaCode;
                model.FieldIDs = FieldIDs;
                model.TableType = Enm.清单类别.设置清单;
                model.Instime = DateTime.Now;
                // model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                model.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                model.TState = Enm.审核状态.同意;
                ctx.Yqd_QuotaTable.Add(model);
            }
            else
            {
                table.FieldIDs = FieldIDs;
                table.TableType = Enm.清单类别.设置清单;
                table.TState = Enm.审核状态.同意;
                // table.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                table.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
            }



            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
        [User]
        public IActionResult AddQuotaNoplanTable()
        {
            var QuotaCode = Form.GetString("QuotaCode");
            var TableID = Form.GetInt("TableID");
            var Quota = ctx.Yqd_Quota.FirstOrDefault(it => it.QuotaCode == QuotaCode && it.IsShow);
            if (Quota == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "指标信息不存在"
                });
            }

            var table = ctx.Yqd_QuotaTable.FirstOrDefault(it => it.TableID == TableID);
            if (table == null)
            {
                var model = new Yqd_QuotaTable();
                model.TaskID = Quota.TaskID;
                model.QuotaCode = Quota.QuotaCode;
                model.FieldIDs = "";
                model.TableType = Enm.清单类别.无清单;
                model.Instime = DateTime.Now;
                // model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                model.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                model.TState = Enm.审核状态.同意;
                ctx.Yqd_QuotaTable.Add(model);
            }
            else
            {
                table.FieldIDs = "";
                table.TableType = Enm.清单类别.无清单;
                table.Instime = DateTime.Now;
                // table.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                table.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                table.TState = Enm.审核状态.同意;
            }

            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public IActionResult GetQuotaTable()
        {
            var QuotaCode = Form.GetString("QuotaCode");
            var QuotaTable = ctx.Yqd_QuotaTable.FirstOrDefault(it => it.QuotaCode == QuotaCode);
            //var Fieldlist = ctx.Yqd_QuotaField.OrderByDescending(it => it.Tactic).ToList();
            //var FieldIDs = Fieldlist.Select(it => new
            //{
            //    it.FieldID,
            //    it.FieldName
            //}).ToList();
            if (QuotaTable == null)
            {
                return this.ToJson(new
                {
                    success = true
                });
            }
            var arr = new ArrayList();
            return this.ToJson(new
            {
                success = true,

                data = new
                {
                    QuotaTable.TState,
                    QuotaTable.TableID,
                    QuotaTable.TableType,
                    QuotaTable.Reason
                }
            });
        }

        [User]
        public IActionResult EditQuotaTableState()
        {
            var TState = (审核状态)Form.GetInt("TState");
            var QuotaCode = Form.GetString("QuotaCode");
            var Reason = Form.GetString("Reason");
            var Quota = ctx.Yqd_QuotaTable.FirstOrDefault(it => it.QuotaCode == QuotaCode);
            Quota.TState = TState;
            Quota.Reason = Reason;
            if (TState == 审核状态.退回)
            {
                Quota.TableType = 清单类别.设置清单;
            }
            Quota.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            var ret = ctx.SaveChanges();
            var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == Quota.TaskID);
            var name = task.TaskName;
            if (TState == 审核状态.退回 && !string.IsNullOrEmpty(Quota.AddEmployeeCode))
            {
                var user = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == Quota.AddEmployeeCode);
                var Q = ctx.Yqd_Quota.FirstOrDefault(it => it.QuotaCode == Quota.QuotaCode && it.IsShow);
                var text = string.Format("您提交的“{0}”任务中的“{1}”指标清单不符合要求，已退回，退回理由：" + Reason + "，请重新提交。（未完成提交，任务状态将变成预警）", task.TaskName, Q.QuotaName);
                var msg = ddService.GetNotification_Text(text);
                var model = new Yqd_MsgLog();
                model.MsgType = 2;
                model.bizMsgId = Quota.TableID + "_" + DateTime.Now.Minute;
                model.receiverIds = user.AccountId.ToString();
                model.msg = msg;
                model.Result = string.IsNullOrWhiteSpace(user.AccountId.ToString()) ? "接收人为空" : ddService.workNotification("", user.AccountId.ToString(), Quota.TableID + "_" + DateTime.Now.Minute, msg, "");
                model.Instime = DateTime.Now;
                ctx.Yqd_MsgLog.Add(model);
                ctx.SaveChanges();
            }
            if (TState == 审核状态.同意)
            {
                var EResult = ctx.Yqd_EvaluateInfo.Where(it => it.TaskID == task.TaskID && it.IsShow && it.TaskStatus > 2);
                if (!EResult.Any(it => it.Evaluate != "指标清单未完善"))
                {
                    task.TaskStatus = (int)任务状态.正常推进;
                }

                var er = EResult.FirstOrDefault(it => it.Evaluate == "指标清单未完善");
                if (er != null)
                {
                    er.IsShow = false;
                }
            }
            else
            {
                task.TaskStatus = (int)任务状态.预警;
            }
            ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true
            });
        }

        [User]
        public IActionResult AddQuotaPlan()
        {
            var QuotaCode = Form.GetString("QuotaCode");
            var PlanData = Form.GetString("PlanDatas").ToJArray();
            var Quota = ctx.Yqd_Quota.FirstOrDefault(it => it.QuotaCode == QuotaCode);
            if (Quota == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "指标信息不存在"
                });
            }
            var lst = new List<Yqd_QuotaPlan>();
            var pids = new List<int>();
            var index = 0;
            var qp = ctx.Yqd_QuotaPlan.Where(it => it.QuotaCode == QuotaCode);
            foreach (var info in PlanData)
            {

                //var PState = (Enm.清单状态)int.Parse(info["PState"].ToString());
                var model = new Yqd_QuotaPlan
                {
                    Name = info["Name"] == null ? "" : info["Name"].ToString(),
                    Street = info["Street"] == null ? "" : info["Street"].ToString(),
                    MapAddress = info["MapAddress"]?.ToString() ?? "",
                    LinkMan = info["LinkMan"] == null ? "" : info["LinkMan"].ToString(),
                    LinkTel = info["LinkTel"] == null ? "" : info["LinkTel"].ToString(),
                    Unit = info["Unit"] == null ? "" : info["Unit"].ToString(),
                    ProgressPlan = info["ProgressPlan"] == null ? "" : info["ProgressPlan"].ToString(),
                    ProgressInfo = info["ProgressInfo"] == null ? "" : info["ProgressInfo"].ToString(),
                    Remarks = info["Remarks"] == null ? "" : info["Remarks"].ToString(),
                    PlanData = info.ToString(),
                    PState = (Enm.清单状态)int.Parse(info["PState"].ToString()),
                    Tactic = index
                };

                if (!string.IsNullOrEmpty(model.Remarks) || !string.IsNullOrEmpty(model.ProgressInfo) || !string.IsNullOrEmpty(model.ProgressPlan) || !string.IsNullOrEmpty(model.Unit) || !string.IsNullOrEmpty(model.Name) || !string.IsNullOrEmpty(model.Street) || !string.IsNullOrEmpty(model.LinkMan) || !string.IsNullOrEmpty(model.LinkTel))
                {
                    if (info["PlanID"] == null)
                    {
                        model.TaskID = Quota.TaskID;
                        model.QuotaCode = Quota.QuotaCode;
                        lst.Add(model);
                    }
                    else
                    {
                        var pid = int.Parse(info["PlanID"].ToString());
                        pids.Add(pid);
                        var p = qp.FirstOrDefault(it => it.PlanID == pid);
                        p.Name = model.Name;
                        p.Street = model.Street;
                        p.MapAddress = model.MapAddress;
                        p.LinkMan = model.LinkMan;
                        p.LinkTel = model.LinkTel;
                        p.Unit = model.Unit;
                        p.ProgressPlan = model.ProgressPlan;
                        p.ProgressInfo = model.ProgressInfo;
                        p.Remarks = model.Remarks;
                        p.PlanData = model.PlanData;
                        p.PState = model.PState;
                        p.Tactic = model.Tactic;
                    }
                    index++;
                }


            }
            var Qt = ctx.Yqd_QuotaTable.FirstOrDefault(it => it.QuotaCode == QuotaCode);
            if (index > 0)
            {
                if (Qt == null)
                {
                    var model = new Yqd_QuotaTable();
                    model.TaskID = Quota.TaskID;
                    model.QuotaCode = Quota.QuotaCode;
                    model.FieldIDs = "";
                    model.TableType = Enm.清单类别.设置清单;
                    model.Instime = DateTime.Now;
                    model.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                    model.TState = Enm.审核状态.同意;
                    ctx.Yqd_QuotaTable.Add(model);
                }
                else
                {
                    Qt.TableType = Enm.清单类别.设置清单;
                    Qt.TState = Enm.审核状态.同意;
                    Qt.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                }
                if (pids.Count() > 0)
                {
                    ctx.Yqd_QuotaPlan.RemoveRange(qp.Where(it => !pids.Contains(it.PlanID)));
                }

            }


            ctx.Yqd_QuotaPlan.AddRange(lst);
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public IActionResult GetQuotaPlanList()
        {
            var sql = "1=1 ";
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", int.MaxValue);
            if (pagesize == 0) pagesize = int.MaxValue;

            var QuotaCode = Form.GetString("QuotaCode");
            //var QPList = ctx.Yqd_QuotaPlan.Where(it => it.QuotaCode == QuotaCode).OrderBy(it => it.Tactic).ToList();
            if (!string.IsNullOrEmpty(QuotaCode))
            {
                sql += $" and [QuotaCode]='{QuotaCode}'";
            }

            var (totalcount, rs) = ctx.Database.SqlPager<Yqd_QuotaPlan>((page - 1) * pagesize, pagesize, "*", sql, "[Tactic] asc");

            var arr = new ArrayList();
            foreach (var QP in rs)
            {
                arr.Add(new
                {
                    QP.PlanID,
                    QP.Name,
                    QP.Street,
                    QP.MapAddress,
                    QP.LinkMan,
                    QP.LinkTel,
                    QP.Unit,
                    QP.ProgressPlan,
                    QP.ProgressInfo,
                    QP.Remarks,
                    QP.PState,
                    QP.PlanData
                });
            }

            return this.ToJson(new
            {
                success = true,
                totalcount,
                data = arr
            });
        }
        [User]
        public IActionResult AddTaskPlanQuestion()
        {
            var TaskID = Form.GetLong("TaskID");
            var datas = Form.GetString("datas").ToJArray();
            var Task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);


            if (Task == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "指标信息不存在"
                });
            }
            var qp = ctx.Yqd_TaskPlanQuestion.Where(it => it.TaskID == TaskID);
            var lst = new List<Yqd_TaskPlanQuestion>();
            foreach (var info in datas)
            {
                if (info["ID"] == null)
                {
                    var model = new Yqd_TaskPlanQuestion
                    {
                        TaskID = Task.TaskID,
                        Question = info["Question"].ToString(),
                        Measure = info["Measure"].ToString(),
                        EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                        InsTime = DateTime.Now
                    };

                    lst.Add(model);
                }
                else
                {
                    var id = int.Parse(info["ID"].ToString());
                    var q = qp.FirstOrDefault(it => it.ID == id);
                    q.Question = info["Question"].ToString();
                    q.Measure = info["Measure"].ToString();
                    q.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                }
            }
            ctx.Yqd_TaskPlanQuestion.AddRange(lst);
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });



        }
        [User]
        public IActionResult GetTaskPlanQuestionList()
        {
            var TaskID = Form.GetLong("TaskID");
            var QPList = ctx.Yqd_TaskPlanQuestion.Where(it => it.TaskID == TaskID).OrderBy(it => it.InsTime).ToList();
            var arr = new ArrayList();
            foreach (var QP in QPList)
            {
                arr.Add(new
                {
                    QP.ID,
                    QP.Question,
                    QP.Measure,
                    InsTime = QP.InsTime.ToString("yyyy-MM-dd")
                });
            }

            return this.ToJson(new
            {
                success = true,
                data = arr
            });
        }

        [User]
        public IActionResult DelTaskPlanQuestion()
        {
            var ID = Form.GetLong("ID");
            var Tpq = ctx.Yqd_TaskPlanQuestion.FirstOrDefault(it => it.ID == ID);

            if (Tpq == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "问题不存在"
                });
            }
            ctx.Yqd_TaskPlanQuestion.Remove(Tpq);
            ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true
            });
        }

        [User]
        public IActionResult GetTaskN_O()
        {
            var TaskID = Form.GetLong("TaskID");
            var qml = ctx.Yqd_QuotaMsg.Where(it => it.TaskID == TaskID && it.IsShow).ToList();
            var qmcode = qml.Select(it => it.QuotaCode);

            var QuotaList = ctx.Yqd_Quota.Where(it => it.TaskID == TaskID && it.IsShow).ToList();
            var Milestone = ctx.Yqd_Milestone.Where(it => it.TaskID == TaskID && it.IsShow).ToList();

            var QuotaList_N = ctx.Yqd_QuotaNew.Where(it => it.TaskID == TaskID && it.IsShow && qmcode.Contains(it.QuotaCode)).ToList();
            var Milestone_N = ctx.Yqd_MilestoneNew.Where(it => it.TaskID == TaskID && it.IsShow && qmcode.Contains(it.TaskQuotaCode)).ToList();

            var Taskinfo = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            var arr = new ArrayList();
            var Narr = new ArrayList();
            foreach (var Q in QuotaList)
            {
                var qm = Milestone.Where(it => it.TaskQuotaCode == Q.QuotaCode).OrderBy(it => it.MilestoneTime).ToList();
                arr.Add(new
                {
                    Q.ds,
                    Q.QuotaName,
                    Q.QuotaCode,
                    Q.ValueUnit,
                    Q.QuotaType,
                    Q.ValueType,
                    Q.StartValue,
                    Q.CurrentValue,
                    Q.TargetValue,
                    Q.Calucation,
                    MList = qm.Select(it => new
                    {
                        it.MilestoneTime,
                        it.TargetValue,
                        MT = it.MilestoneTime.ToString("M月")
                    }),
                    MsgList = qml.Where(it => it.QuotaCode == Q.QuotaCode && it.IsShow).Select(it => new
                    {
                        it.ds,
                        it.Msg
                    })
                });
            }

            foreach (var Q in QuotaList_N)
            {
                var qm = Milestone_N.Where(it => it.TaskQuotaCode == Q.QuotaCode).OrderBy(it => it.MilestoneTime).ToList();
                var oqm = Milestone.Where(it => it.TaskQuotaCode == Q.QuotaCode).OrderBy(it => it.MilestoneTime).ToList();
                //if (qm.Count() ==0)
                //{
                //    qm = Milestone.Where(it => it.TaskQuotaCode == Q.QuotaCode).OrderBy(it => it.MilestoneTime).ToList();
                //}
                Narr.Add(new
                {
                    Q.ds,
                    Q.QuotaName,
                    Q.QuotaCode,
                    Q.ValueUnit,
                    Q.QuotaType,
                    Q.ValueType,
                    Q.StartValue,
                    Q.CurrentValue,
                    Q.TargetValue,
                    Q.Calucation,
                    MList = qm.Count() == 0 ? (oqm.Select(it => new
                    {
                        it.MilestoneTime,
                        it.TargetValue,
                        MT = it.MilestoneTime.ToString("M月")
                    })) : (qm.Select(it => new
                    {
                        it.MilestoneTime,
                        it.TargetValue,
                        MT = it.MilestoneTime.ToString("M月")
                    }))

                });
            }

            return this.ToJson(new
            {
                success = true,
                Taskinfo.TaskName,
                data_O = arr,
                data_N = Narr
            });

        }

        [User]
        public IActionResult upNewsData()
        {
            var TaskID = Form.GetLong("TaskID");

            var QuotaList = ctx.Yqd_Quota.Where(it => it.TaskID == TaskID && it.IsShow);
            var NQuotaList = ctx.Yqd_QuotaNew.Where(it => it.TaskID == TaskID && it.IsShow);
            var MilestoneList = ctx.Yqd_Milestone.Where(it => it.TaskID == TaskID && it.IsShow);
            var NMilestoneList = ctx.Yqd_MilestoneNew.Where(it => it.TaskID == TaskID && it.IsShow);
            var qMsg = ctx.Yqd_QuotaMsg.Where(it => it.TaskID == TaskID);
            var Task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            var AQL = new List<Yqd_Quota>();
            var AML = new List<Yqd_Milestone>();
            foreach (var Q in QuotaList)
            {
                var isQMsg = qMsg.Any(it => it.QuotaCode == Q.QuotaCode && it.TField == "Yqd_Quota");

                if (isQMsg)
                {
                    var NQ = NQuotaList.FirstOrDefault(it => it.QuotaCode == Q.QuotaCode);
                    Q.IsShow = false;

                    if (NQ.QuotaID == Q.QuotaID)
                    {
                        Q.QuotaName = NQ.QuotaName;
                        Q.QuotaCode = NQ.QuotaCode;
                        Q.TaskID = NQ.TaskID;
                        Q.QuotaID = NQ.QuotaID;
                        Q.QuotaType = NQ.QuotaType;
                        Q.TargetValue = NQ.TargetValue;
                        Q.CurrentValue = NQ.CurrentValue;
                        Q.StartValue = NQ.StartValue;
                        Q.ValueType = NQ.ValueType;
                        Q.ValueUnit = NQ.ValueUnit;
                        Q.QuotaDesc = NQ.QuotaDesc;
                        Q.Calucation = NQ.Calucation;
                        Q.ds = NQ.ds;
                        Q.CreateTime = NQ.CreateTime;
                        Q.Tactic = NQ.Tactic;
                        Q.IsShow = NQ.IsShow;
                        Q.Creator = NQ.Creator;
                        Q.InsTime = NQ.InsTime;

                    }
                    else
                    {
                        AQL.Add(new Yqd_Quota
                        {
                            QuotaName = NQ.QuotaName,
                            QuotaCode = NQ.QuotaCode,
                            TaskID = NQ.TaskID,
                            QuotaID = NQ.QuotaID,
                            QuotaType = NQ.QuotaType,
                            TargetValue = NQ.TargetValue,
                            CurrentValue = NQ.CurrentValue,
                            StartValue = NQ.StartValue,
                            ValueType = NQ.ValueType,
                            ValueUnit = NQ.ValueUnit,
                            QuotaDesc = NQ.QuotaDesc,
                            Calucation = NQ.Calucation,
                            ds = NQ.ds,
                            CreateTime = NQ.CreateTime,
                            Tactic = NQ.Tactic,
                            IsShow = NQ.IsShow,
                            Creator = NQ.Creator,
                            InsTime = NQ.InsTime
                        });

                    }
                    NQ.IsShow = false;
                }

                var isMMsg = qMsg.Any(it => it.QuotaCode == Q.QuotaCode && it.TField == "Yqd_Milestone");

                if (isMMsg)
                {
                    var NML = NMilestoneList.Where(it => it.TaskQuotaCode == Q.QuotaCode);
                    var ML = MilestoneList.Where(it => it.TaskQuotaCode == Q.QuotaCode);
                    foreach (var NM in NML)
                    {

                        AML.Add(new Yqd_Milestone
                        {
                            TaskID = NM.TaskID,
                            MilestoneID = NM.MilestoneID,
                            TaskQuotaCode = NM.TaskQuotaCode,
                            TargetValue = NM.TargetValue,
                            MilestoneTime = NM.MilestoneTime,
                            ds = NM.ds,
                            IsShow = NM.IsShow,
                            InsTime = NM.InsTime,
                            Tactic = NM.Tactic,
                            Creator = NM.Creator
                        });
                        NM.IsShow = false;
                    }

                    foreach (var M in ML)
                    {
                        M.IsShow = false;
                    }

                }

            }
            ctx.Yqd_Quota.AddRange(AQL);
            ctx.Yqd_Milestone.AddRange(AML);
            Task.TaskStatus = (int)Enm.任务状态.其他;
            if (TaskID > 0)
            {

                var sql = string.Format("update Yqd_QuotaMsg set IsShow = 0 where TaskID in ({0})", TaskID);
                ctx.Database.ExecuteSql(sql);

                var sql1 = string.Format("update Yqd_EvaluateInfo set IsShow = 0 where DataTable='QuotaMsg' and  TaskID in ({0})", TaskID);
                ctx.Database.ExecuteSql(sql1);
            }

            var r = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true
            });



        }

        [User]

        public IActionResult AddTaskError(Yqd_TaskError model)
        {
            var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == model.TaskID);
            if (task == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "任务信息不存在"
                });
            }
            if (model.EvaluateInfoID > 0)
            {
                var ise = ctx.Yqd_EvaluateInfo.FirstOrDefault(it => it.ID == model.EvaluateInfoID);
                if (ise == null)
                {
                    return this.ToJson(new
                    {
                        success = false,
                        msg = "该条考核不存在"
                    });
                }
            }
            model.Instime = DateTime.Now;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            ctx.Yqd_TaskError.Add(model);
            task.ots = task.TaskStatus;
            task.TaskStatus = (int)任务状态.其他;
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });

        }

        [User]
        public IActionResult DelTaskError()
        {
            var ID = Form.GetLong("ID");
            var TaskE = ctx.Yqd_TaskError.FirstOrDefault(it => it.ID == ID);
            if (TaskE != null)
            {
                var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskE.TaskID);
                //var er=ctx
                task.TaskStatus = task.ots.Value;
                ctx.Yqd_TaskError.Remove(TaskE);
            }
            var ret = ctx.SaveChanges();
            //var ret = ctx.Database.ExecuteSql("delete from Yqd_TaskError where ID={0}", ID);
            return this.ToJson(new
            {
                success = true,
                ret
            });

        }

        public IActionResult Test()
        {
            var nt = DateTime.Now;
            var arr = "2023-02-11".Split(",");
            var dt = DateTime.Parse(arr[arr.Length - 1]);
            var ee = dt.AddDays(-3);
            var t22 = DateTime.Parse("2023-02-08 10:00:00");
            var b = t22 >= ee && t22 < dt;
            nt = nt.Date;
            var xx = dt.Subtract(nt).Days;

            var t = DateTime.Parse("2023-02-08");
            var xx11 = dt.Subtract(t).Days < 4;


            var t1 = DateTime.Parse("2023-02-07");
            var xx111 = dt.Subtract(t1).Days < 4;

            var ddService = Fn.GetService<DdService>();
            //Logs.Warning<RankService>("开始推送效能报告");

            //var MaxResultTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
            //var newRankList = ctx.Yqd_Rank.Where(it => it.ResultTime == MaxResultTime).OrderBy(x => x.Tactic).ToList();
            //if (!newRankList.Any())
            //{
            //    var where = "SELECT LeaderUnitCode as UnitCode, LeaderUnitName as UnitName, TaskStatus, COUNT(*) AS Num FROM Yqd_Task WHERE IsShow = 1  and [Year]=" + DateTime.Now.Year;

            //    where += " GROUP BY LeaderUnitCode,LeaderUnitName,TaskStatus";
            //    where += " ORDER BY LeaderUnitCode,LeaderUnitName,TaskStatus";
            //    var list = ctx.Database.SqlQuery<TaskStatusTJ>(where).ToList();
            //    var unit = list.Select(it => new
            //    {
            //        it.UnitCode,
            //        it.UnitName
            //    }).Distinct();
            //    var IRL = ctx.Yqd_IntegralRule.ToList();
            //    var WCV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.已完成).Value;
            //    var ZCV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.正常推进).Value;
            //    var YJV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.预警).Value;
            //    var ZHV = IRL.FirstOrDefault(it => it.IntegralRuleID == 任务状态.滞后).Value;
            //    if (unit.Any())
            //    {
            //        Logs.Warning<RankService>("判断有数据可以推送");
            //    }
            //    var RankList = new List<Yqd_Rank>();
            //    foreach (var m in unit)
            //    {
            //        var ml = list.Where(it => it.UnitCode == m.UnitCode);
            //        var Count = ml.Sum(it => it.Num);
            //        var WC = ml.FirstOrDefault(it => it.TaskStatus == (int)任务状态.已完成)?.Num ?? 0;
            //        var ZC = ml.FirstOrDefault(it => it.TaskStatus == (int)任务状态.正常推进)?.Num ?? 0;
            //        var YJ = ml.FirstOrDefault(it => it.TaskStatus == (int)任务状态.预警)?.Num ?? 0;
            //        var ZH = ml.FirstOrDefault(it => it.TaskStatus == (int)任务状态.滞后)?.Num ?? 0;
            //        //完成的总积分
            //        var WCS = WC * WCV;
            //        //正常的总积分
            //        var ZCS = ZC * ZCV;
            //        //预警的总积分
            //        var YJS = YJ * YJV;
            //        //预警的总积分
            //        var ZHS = ZH * ZHV;
            //        //计算平均分
            //        var AvgScore = Count == 0 ? 0 : (WCS + ZCS + YJS + ZHS) / Count;
            //        var Score = Math.Round(AvgScore, 2);
            //        var task = ctx.Yqd_Task.Where(x => x.LeaderUnitCode == m.UnitCode).OrderByDescending(x => x.InsTime).FirstOrDefault();
            //        RankList.Add(new Yqd_Rank
            //        {
            //            RankID = 0,
            //            Name = m.UnitName,
            //            UnitCode = m.UnitCode,
            //            Score = Score,
            //            Count = Count,
            //            ResultTime = task.InsTime,
            //            WC = WC,
            //            ZC = ZC,
            //            YJ = YJ,
            //            ZH = ZH
            //        });
            //    }
            //    var addList = new List<Yqd_Rank>();
            //    var result = RankList.OrderByDescending(it => it.Score).ThenByDescending(it => it.Count).ThenByDescending(it => it.ResultTime).Take(250).ToList();
            //    Logs.Warning<RankService>("新增排名" + result.Count + "条");
            //    foreach (var item in result)
            //    {
            //        var rank = item;
            //        rank.Tactic = result.IndexOf(item) + 1;
            //        rank.ResultTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
            //        addList.Add(rank);
            //    }
            //    if (addList.Count() > 0) { ctx.Yqd_Rank.AddRange(addList); }
            //    var ret = ctx.SaveChanges();

            //    newRankList = ctx.Yqd_Rank.Where(it => it.ResultTime == MaxResultTime).OrderBy(x => x.Tactic).ToList();
            //}
            //var IP = "123.156.65.12";
            //var msglist = new List<Yqd_MsgLog>();
            //foreach (var item in newRankList)
            //{
            //    try
            //    {
            //        var unitList = ctx.Yqd_Unit.Where(it => item.UnitCode == it.UnitCode).ToList();
            //        var OC = unitList.Select(it => it.OrganizationCode).ToList();
            //        var user = ctx.Yqd_User.Where(it => OC.Contains(it.UnitCode) && it.AccountId > 0 && (("," + it.PermitItem + ",").Contains("," + (int)权限清单.接收效能评价报告 + ","))).ToList();
            //        var msg = ddService.GetNotification_OA(item);
            //        var ZUC = unitList.FirstOrDefault(it => it.UnitCode == item.UnitCode);
            //        var Userlist = user.Where(it => it.UnitCode == ZUC.OrganizationCode).Select(it => it.AccountId);
            //        var receiverIds = string.Join(",", Userlist);
            //        if (item.UnitCode == "330782000000")
            //        {
            //            receiverIds = string.Join(",", user.Where(it => ("," + it.PermitItem + ",").Contains("," + (int)权限清单.接收效能评价报告 + ",")).Select(it => it.AccountId));
            //        }
            //        Logs.Warning<RankService>($"接收人：{receiverIds}，单位：" + item.Name);
            //        //receiverIds = "31028423,79182855,10895460";
            //        var model = new Yqd_MsgLog();
            //        model.MsgType = 1;
            //        model.bizMsgId = item.RankID.ToString();
            //        model.receiverIds = receiverIds;
            //        model.msg = msg;
            //        model.Result = string.IsNullOrWhiteSpace(receiverIds) ? "接收人为空" : ddService.workNotification("", receiverIds, item.RankID.ToString(), msg, IP);
            //        model.Instime = DateTime.Now;
            //        msglist.Add(model);
            //    }
            //    catch (Exception e)
            //    {
            //        Logs.Warning<RankService>(" 莫名其妙报错了{0},Source:{1},InnerException{2},TargetSite:{3},StackTrace:{4}", e.Message, e.Source, e.InnerException, e.TargetSite, e.StackTrace);
            //    }
            //}
            //if (msglist.Count() > 0) { ctx.Yqd_MsgLog.AddRange(msglist); ctx.SaveChanges(); }
            //Logs.Warning<RankService>("部门效能报告推送完成！本次更新" + msglist.Count() + "条");

            //////   public JObject workNotification(string organizationCodes, string receiverIds, int tenantId,string bizMsgId, string msg)
            ////// var msg = "{'msgtype':'text','text':{'content': '给吴剑飞和金梦娇的测试消息'}}";


            //////var msg = JObject.FromObject(new {
            //////    msgtype ="text",
            //////    text= JObject.FromObject(new {
            //////        content= "给吴剑飞和金梦娇的测试消息"
            //////    })
            //////}).ToString();

            //////var arr =new ArrayList();
            //////arr.Add(new
            //////{
            //////    key = "效能指数",
            //////    value= "83.71"
            //////}) ;
            //////arr.Add(new
            //////{
            //////    key = "全市排名",
            //////    value = "14"
            //////});

            ////var Rank = ctx.Yqd_Rank.FirstOrDefault(it => it.RankID == 1699);
            ////var msg = ddService.GetNotification_OA(Rank);
            ////var unit = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == Rank.UnitCode);

            //////I9Fmrp36JM5W0FJ3qP12oO4o06HYx30Ya6KD427l
            //////GoJ8TI7569LeaaE7X33etAt920eP15kSr17AldUP

            ////var user = ctx.Yqd_User.Where(it => it.UnitCode == unit.OrganizationCode && it.AccountId > 0 && ("," + it.Roles + ",").Contains("," + (int)角色类型.部门管理员 + ","));


            ////var receiverIds = string.Join(",", user.Select(it => it.AccountId));

            ////var data = ddService.workNotification("", receiverIds, Rank.RankID+"_1", msg);
            return this.ToJson(new
            {
                success = true,
                //   data = data
            });
        }

        [User]
        public ActionResult Import()
        {
            var fn = Form.GetString("fn");
            var TaskID = Form.GetLong("TaskID", 0);
            var QuotaCode = Form.GetString("QuotaCode");
            var q = ctx.Yqd_Quota.FirstOrDefault(it => it.QuotaCode == QuotaCode);
            if (TaskID == 0)
            {
                TaskID = q.TaskID;
            }

            var path = Config.Yqdpath("/");
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

            FileInfo file = new FileInfo(path + fn);
            Logs.Warning<ZLDHomeController>("file:" + path + fn);
            Logs.Warning<ZLDHomeController>("FullName:" + file.FullName);
            var index = 0;
            if (file != null)
            {
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets["Sheet1"];
                    int rowCount = worksheet.Dimension.Rows;
                    int ColCount = worksheet.Dimension.Columns;
                    // var fields = ctx.Yqd_SpecialTemplate.Where(it => it.IsGeneral || (it.TaskID == TaskID && it.TypeID == TypeID)).OrderBy(it => it.Tactic).Select(it => new { it.FieldID, it.Name }).ToList();
                    var record = new Dictionary<string, string>();
                    var yqpl = new List<Yqd_QuotaPlan>();
                    for (var row = 2; row <= rowCount; row++)
                    {
                        record.Clear();
                        var model = new Yqd_QuotaPlan();
                        model.TaskID = TaskID;
                        model.QuotaCode = QuotaCode;

                        try
                        {
                            model.Name = worksheet.Cells[row, 1].Value.ToString().Trim();
                        }
                        catch
                        {
                            model.Name = "";
                        }
                        try
                        {
                            model.Street = worksheet.Cells[row, 2].Value.ToString().Trim();
                        }
                        catch
                        {
                            model.Street = "";
                        }

                        try
                        {
                            model.MapAddress = worksheet.Cells[row, 3].Value.ToString().Trim();
                        }
                        catch
                        {
                            model.MapAddress = "";
                        }

                        try
                        {
                            model.Unit = worksheet.Cells[row, 4].Value.ToString().Trim();
                        }
                        catch
                        {
                            model.Unit = "";
                        }

                        try
                        {
                            model.LinkMan = worksheet.Cells[row, 5].Value.ToString().Trim();
                        }
                        catch
                        {
                            model.LinkMan = "";
                        }

                        try
                        {
                            model.LinkTel = worksheet.Cells[row, 6].Value.ToString().Trim();
                        }
                        catch
                        {
                            model.LinkTel = "";
                        }

                        try
                        {
                            var P = worksheet.Cells[row, 7].Value.ToString().Trim();
                            model.PState = P == "未启动" ? 清单状态.未启动 : (P == "推进中" ? 清单状态.推进中 : 清单状态.已完成);
                        }
                        catch
                        {
                            model.PState = 清单状态.未启动;
                        }

                        try
                        {
                            model.ProgressPlan = worksheet.Cells[row, 8].Value.ToString().Trim();
                        }
                        catch
                        {
                            model.ProgressPlan = "";
                        }

                        try
                        {
                            model.ProgressInfo = worksheet.Cells[row, 9].Value.ToString().Trim();
                        }
                        catch
                        {
                            model.ProgressInfo = "";
                        }

                        try
                        {
                            model.Remarks = worksheet.Cells[row, 10].Value.ToString().Trim();
                        }
                        catch
                        {
                            model.Remarks = "";
                        }

                        model.Tactic = index;
                        if (!string.IsNullOrEmpty(model.Remarks) || !string.IsNullOrEmpty(model.ProgressInfo) || !string.IsNullOrEmpty(model.ProgressPlan) || !string.IsNullOrEmpty(model.Unit) || !string.IsNullOrEmpty(model.Name) || !string.IsNullOrEmpty(model.Street) || !string.IsNullOrEmpty(model.LinkMan) || !string.IsNullOrEmpty(model.LinkTel))
                        {
                            // ctx.Yqd_QuotaPlan.Add(model);
                            yqpl.Add(model);
                            index++;
                        }

                    }

                    if (yqpl.Count() > 0)
                    {
                        ctx.Yqd_QuotaPlan.AddRange(yqpl);
                        var Qt = ctx.Yqd_QuotaTable.FirstOrDefault(it => it.QuotaCode == QuotaCode);
                        if (index > 0)
                        {
                            if (Qt == null)
                            {
                                var model = new Yqd_QuotaTable();
                                model.TaskID = TaskID;
                                model.QuotaCode = QuotaCode;
                                model.FieldIDs = "";
                                model.TableType = 清单类别.设置清单;
                                model.Instime = DateTime.Now;
                                model.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                                model.TState = 审核状态.同意;
                                ctx.Yqd_QuotaTable.Add(model);
                            }
                            else
                            {
                                Qt.TableType = 清单类别.设置清单;
                                Qt.TState = 审核状态.同意;
                                Qt.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                            }
                        }

                    }


                    var ret = ctx.SaveChanges();
                    return this.ToJson(new
                    {
                        success = true,
                        ret
                    });
                }
            }
            return this.ToJson(new
            {
                success = false
            });
        }

        [User]
        public ActionResult GetJKList()
        {
            var type = Form.GetString("type", "all");
            var det = ctx.detection_rsj_rczb_data.Where(it => it.type == type).ToList();
            if (type == "all")
            {
                return this.ToJson(new
                {
                    success = true,
                    data = det.Select(it => new
                    {
                        it.rcmffl,
                        it.fwrc,
                        it.rcywsql,
                        it.shtgl
                    })
                    //   data = data
                });
            }
            else
            {
                return this.ToJson(new
                {
                    success = true,
                    data = det.Select(it => new
                    {
                        it.name,
                        it.number,
                        it.unit
                    })
                    //   data = data
                });
            }
        }


    }
}
